1 /* 2 * Copyright (C) 2007 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.dexgen.util; 18 19 import java.io.File; 20 import java.io.FileInputStream; 21 import java.io.IOException; 22 23 /** 24 * File I/O utilities. 25 */ 26 public final class FileUtils { 27 /** 28 * This class is uninstantiable. 29 */ 30 private FileUtils() { 31 // This space intentionally left blank. 32 } 33 34 /** 35 * Reads the named file, translating {@link IOException} to a 36 * {@link RuntimeException} of some sort. 37 * 38 * @param fileName {@code non-null;} name of the file to read 39 * @return {@code non-null;} contents of the file 40 */ 41 public static byte[] readFile(String fileName) { 42 File file = new File(fileName); 43 return readFile(file); 44 } 45 46 /** 47 * Reads the given file, translating {@link IOException} to a 48 * {@link RuntimeException} of some sort. 49 * 50 * @param file {@code non-null;} the file to read 51 * @return {@code non-null;} contents of the file 52 */ 53 public static byte[] readFile(File file) { 54 if (!file.exists()) { 55 throw new RuntimeException(file + ": file not found"); 56 } 57 58 if (!file.isFile()) { 59 throw new RuntimeException(file + ": not a file"); 60 } 61 62 if (!file.canRead()) { 63 throw new RuntimeException(file + ": file not readable"); 64 } 65 66 long longLength = file.length(); 67 int length = (int) longLength; 68 if (length != longLength) { 69 throw new RuntimeException(file + ": file too long"); 70 } 71 72 byte[] result = new byte[length]; 73 74 try { 75 // convert to try-with-resources once dexgen uses an Android API 19+ which supports it 76 FileInputStream in = new FileInputStream(file); 77 try { 78 int at = 0; 79 while (length > 0) { 80 int amt = in.read(result, at, length); 81 if (amt == -1) { 82 throw new RuntimeException(file + ": unexpected EOF"); 83 } 84 at += amt; 85 length -= amt; 86 } 87 } finally { 88 in.close(); 89 } 90 } catch (IOException ex) { 91 throw new RuntimeException(file + ": trouble reading", ex); 92 } 93 94 return result; 95 } 96 } 97