FileUtils.java (1261B)
1 /** 2 * 3 */ 4 package de.openrat.android.blog; 5 6 import java.io.File; 7 import java.io.FileInputStream; 8 import java.io.IOException; 9 import java.io.InputStream; 10 11 /** 12 * @author dankert 13 * 14 */ 15 public class FileUtils 16 { 17 18 /** 19 * 20 * @param file 21 * @return 22 * @throws IOException 23 */ 24 public static byte[] getBytesFromFile(File file) throws IOException { 25 InputStream is = new FileInputStream(file); 26 27 // Get the size of the file 28 long length = file.length(); 29 30 if (length > Integer.MAX_VALUE) { 31 // File is too large 32 throw new IOException("File is too large"); 33 } 34 35 // Create the byte array to hold the data 36 byte[] bytes = new byte[(int)length]; 37 38 // Read in the bytes 39 int offset = 0; 40 int numRead = 0; 41 while (offset < bytes.length 42 && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) { 43 offset += numRead; 44 } 45 46 // Ensure all the bytes have been read in 47 if (offset < bytes.length) { 48 throw new IOException("Could not completely read file "+file.getName()); 49 } 50 51 // Close the input stream and return bytes 52 is.close(); 53 return bytes; 54 } 55 }