This example will show how to read the contents of a file into a byte array using java, java 7 NIO , guava, and apache commons.
private static final String FILE_PATH = "com/levelup/java/io/file-to-byte-array.txt"; private URI fileLocation; @Before public void setUp() throws URISyntaxException { fileLocation = this.getClass().getClassLoader().getResource(FILE_PATH).toURI(); }
File to byte array
@Test public void file_to_byte_array_java () throws IOException { File file = new File(fileLocation); byte[] fileInBytes = new byte[(int) file.length()]; InputStream inputStream = null; try { inputStream = new FileInputStream(file); inputStream.read(fileInBytes); } finally { inputStream.close(); } assertEquals(18, fileInBytes.length); }
@Test public void file_to_byte_array_java_nio () throws IOException { Path path = Paths.get(fileLocation); byte[] fileInBytes = java.nio.file.Files.readAllBytes(path); assertEquals(18, fileInBytes.length); }
@Test public void file_to_byte_array_guava () throws IOException, URISyntaxException { File file = new File(fileLocation); byte[] fileInBytes = Files.toByteArray(file); assertEquals(18, fileInBytes.length); }
@Test public void file_to_byte_array_guava_byteStreams () throws IOException { File file = new File(fileLocation); InputStream filestream = new FileInputStream(file); byte[] fileInBytes = ByteStreams.toByteArray(filestream); assertEquals(18, fileInBytes.length); }
@Test public void file_to_byte_array_apache () throws IOException { File file = new File(fileLocation); byte[] fileInBytes = FileUtils.readFileToByteArray(file); assertEquals(18, fileInBytes.length); }
@Test public void file_to_byte_array_apache_ioutils () throws IOException { byte[] fileInBytes = IOUtils.toByteArray(fileLocation); assertEquals(18, fileInBytes.length); }