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 dxconvext.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 non-null; name of the file to read 39 * @return 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 non-null; the file to read 51 * @return 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 FileInputStream in = new FileInputStream(file); 76 int at = 0; 77 while (length > 0) { 78 int amt = in.read(result, at, length); 79 if (amt == -1) { 80 throw new RuntimeException(file + ": unexpected EOF"); 81 } 82 at += amt; 83 length -= amt; 84 } 85 in.close(); 86 } catch (IOException ex) { 87 throw new RuntimeException(file + ": trouble reading", ex); 88 } 89 90 return result; 91 } 92 } 93