// Returns the contents of the file in a byte array.public static byte[] getBytesFromFile(File file) throws IOException {// Get the size of the filelong length = file.length();
// You cannot create an array using a long type.// It needs to be an int type.// Before converting to an int type, check// to ensure that file is not larger than Integer.MAX_VALUE.if (length > Integer.MAX_VALUE) {// File is too largethrow new IOException("File is too large!");}
// Create the byte array to hold the databyte[] bytes = new byte[(int)length];
// Read in the bytesint offset = 0;int numRead = 0;
InputStream is = new FileInputStream(file);try {while (offset < bytes.length&& (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {offset += numRead;}} finally {is.close();}
// Ensure all the bytes have been read inif (offset < bytes.length) {throw new IOException("Could not completely read file "+file.getName());}return bytes;}
public static byte[] readFileToByteArray(File file) throws IOException
示例使用(Program.java):
import org.apache.commons.io.FileUtils;public class Program {public static void main(String[] args) throws IOException {File file = new File(args[0]); // assume args[0] is the path to filebyte[] data = FileUtils.readFileToByteArray(file);...}}
File fff = new File("/path/to/file");FileInputStream fileInputStream = new FileInputStream(fff);
// int byteLength = fff.length();
// In android the result of file.length() is longlong byteLength = fff.length(); // byte count of the file-content
byte[] filecontent = new byte[(int) byteLength];fileInputStream.read(filecontent, 0, (int) byteLength);
//The file that you wanna convert into byte[]File file=new File("/storage/0CE2-EA3D/DCIM/Camera/VID_20190822_205931.mp4");
FileInputStream fileInputStream=new FileInputStream(file);byte[] data=new byte[(int) file.length()];BufferedInputStream bufferedInputStream=new BufferedInputStream(fileInputStream);bufferedInputStream.read(data,0,data.length);
//Now the bytes of the file are contain in the "byte[] data"