Here you can find the source of getBytesFromFile(File inputFile)
This method reads a file and convert it into bytes
Parameter | Description |
---|---|
inputFile | File to be read |
Parameter | Description |
---|---|
FileNotFoundException | If file is not found |
IOException | Any error occurred during the operation |
public static byte[] getBytesFromFile(File inputFile) throws IOException
//package com.java2s; //License from project: LGPL import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; public class Main { /**//from ww w . ja v a 2s . c o m * <p> * This method reads a file and convert it into bytes * </p> * * @param inputFile * File to be read * @return bytes read from the file * @throws FileNotFoundException * If file is not found * @throws IOException * Any error occurred during the operation */ public static byte[] getBytesFromFile(File inputFile) throws IOException { InputStream inputStream = new FileInputStream(inputFile); long length = inputFile.length(); // Create the byte array to hold the data byte[] outputBytes = new byte[(int) length]; // Read in the bytes int offset = 0; int numRead = 0; if (offset < outputBytes.length) { numRead = inputStream.read(outputBytes, offset, outputBytes.length - offset); while (offset < outputBytes.length && numRead >= 0) { offset += numRead; numRead = inputStream.read(outputBytes, offset, outputBytes.length - offset); } } // Ensure all the bytes have been read in if (offset < outputBytes.length) { throw new IOException("Could not completely read file " + inputFile.getName()); } // Close the input stream and return bytes inputStream.close(); return outputBytes; } }