File to byte array

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.

Setup

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 contents

File to byte array

Straight up Java

FileInputStream

@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);
}

Java 7 File I/O

@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);
}

Google Guava

Files

@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);
}

ByteStreams

@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);
}

Apache Commons

FileUtils

@Test
public void file_to_byte_array_apache () throws IOException {

    File file = new File(fileLocation);

    byte[] fileInBytes = FileUtils.readFileToByteArray(file);

    assertEquals(18, fileInBytes.length);
}

IOUtils

@Test
public void file_to_byte_array_apache_ioutils () throws IOException {

    byte[] fileInBytes = IOUtils.toByteArray(fileLocation);

    assertEquals(18, fileInBytes.length);
}