Read Files with Files.readAllBytes() in Java

Alexey Karimov

Trying to read the entire contents of a file in one go, whether it’s for a quick configuration check, a test case, or just to load a complete log into memory? Then you might want to try Files.readAllBytes().

This method is from the java.nio.file.Files class. It reads all the bytes from a file and returns them as a byte array. Plus, it provides a simple way to load file content into memory for further processing. 

The best part is that it also handles opening and closing the file stream, so you don’t have to manage it manually. The method throws an IOException if the file can’t be read or accessed.

When To Use Files.readAllBytes()

Learning where to use Files.readAllBytes() helps make the implementation cleaner and avoids unnecessary complications, especially when dealing with small, predictable files. Since this method reads the entire file content into memory, it works best when the file size and structure are known ahead of time.

Here are some ideal use cases:

  • Reading configuration files, logs, or static assets in a utility script.
  • Quickly loading test fixtures or resource files in unit tests.
  • Parsing file contents that don’t require partial or incremental reading.
  • Scenarios where the file size is small enough to avoid memory concerns.
  • When you want to avoid managing open/close operations explicitly.

How To Use Files.readAllBytes() With Examples

To use Files.readAllBytes(), you need to pass a Path object that points to the file you want to read. The method reads the entire content and returns it as a byte array. 

static byte[] readAllBytes(Path path) throws IOException 

For better understanding, here are two examples that show how Files.readAllBytes() can be used in different file-reading scenarios.

Example 1: Reading a Text File

First, let’s look at a text file. This example writes a few lines to a file, then reads the entire content using Files.readAllBytes() and converts it into a readable string:

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Arrays;
import java.util.List;

public class TextFileReadExample {

    public static void main(String[] args) {
        Path path = Paths.get("example.txt");
        List<String> lines = Arrays.asList("First line", "Second line");

        // Write text to the file
        try {
            Files.write(path, lines, StandardCharsets.UTF_8,
                        StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
        } catch (IOException e) {
            System.out.println("Write error: " + e.getMessage());
        }

        // Read entire file content as bytes and convert to String
        try {
            byte[] contentBytes = Files.readAllBytes(path);
            String content = new String(contentBytes, StandardCharsets.UTF_8);
            System.out.println(content);
        } catch (IOException e) {
            System.out.println("Read error: " + e.getMessage());
        }
    }
}

Example 2: Reading a Binary File

Next, let’s look at reading a binary file. This example writes a byte array to a .bin file and then reads it back using Files.readAllBytes():

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Arrays;

public class BinaryFileReadExample {

    public static void main(String[] args) {
        Path path = Paths.get("data.bin");
        byte[] dataToWrite = {10, 20, 30, 40, 50};

        // Write binary data to the file
        try {
            Files.write(path, dataToWrite,
                        StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
        } catch (IOException e) {
            System.out.println("Write error: " + e.getMessage());
        }

        // Read binary data from the file
        try {
            byte[] fileContent = Files.readAllBytes(path);
            System.out.println(Arrays.toString(fileContent));
        } catch (IOException e) {
            System.out.println("Read error: " + e.getMessage());
        }
    }
}
icon You can follow this approach when you need a File object from a resource. Alternatively, when working in environments where resources are packaged in a directory structure (e.g., during local development).

Wrapping Up

Files.readAllBytes() is a quick and practical method for reading small files into memory, ideal for use cases like config loading, testing, or working with static data. For reading large files, consider using BufferedReader, Scanner, or streaming approaches that process data in chunks instead of all at once.

Also worth noting: If you’re working with an InputStream instead of a Path, Java 9 introduced InputStream.readAllBytes(). It behaves similarly but is suited for data coming from sources like HTTP responses, in-memory buffers, or manually opened streams.