Elegant way to read file into byte[] array in Java [duplicate]
A long time ago:
Call any of these
byte[] org.apache.commons.io.FileUtils.readFileToByteArray(File file)byte[] org.apache.commons.io.IOUtils.toByteArray(InputStream input)
From
If the library footprint is too big for your Android app, you can just use relevant classes from the commons-io library
Today (Java 7+ or Android API Level 26+)
Luckily, we now have a couple of convenience methods in the nio packages. For instance:
byte[] java.nio.file.Files.readAllBytes(Path path)
This will also work:
import java.io.*;public class IOUtil { public static byte[] readFile(String file) throws IOException { return readFile(new File(file)); } public static byte[] readFile(File file) throws IOException { // Open file RandomAccessFile f = new RandomAccessFile(file, "r"); try { // Get and check length long longlength = f.length(); int length = (int) longlength; if (length != longlength) throw new IOException("File size >= 2 GB"); // Read file and return data byte[] data = new byte[length]; f.readFully(data); return data; } finally { f.close(); } }}
If you use Google Guava (and if you don't, you should), you can call: ByteStreams.toByteArray(InputStream)
or Files.toByteArray(File)