File to byte[] in Java File to byte[] in Java java java

File to byte[] in Java


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());


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).


Since JDK 7 - one liner:

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

No external dependencies needed.