File to byte[] in Java – Dev

The best answers to the question “File to byte[] in Java” in the category Dev.

QUESTION:

How do I convert a java.io.File to a byte[]?

ANSWER:

It depends on what best means for you. Productivity wise, don’t reinvent the wheel and use Apache Commons. Which is here FileUtils.readFileToByteArray(File input).

ANSWER:

From JDK 7 you can use Files.readAllBytes(Path).

Example:

import java.io.File;
import java.nio.file.Files;

File file;
// ...(file is initialised)...
byte[] fileContent = Files.readAllBytes(file.toPath());

ANSWER:

import java.io.RandomAccessFile;
RandomAccessFile f = new RandomAccessFile(fileName, "r");
byte[] b = new byte[(int)f.length()];
f.readFully(b);

Documentation for Java 8: http://docs.oracle.com/javase/8/docs/api/java/io/RandomAccessFile.html

ANSWER:

Since JDK 7 – one liner:

byte[] array = Files.readAllBytes(Paths.get("/path/to/file"));

No external dependencies needed.