How to read a file using Files.readAllBytes() in Java

The Files.readAllBytes() static method is a part of Java's non-blocking new I/O API (NIO). It can be used to read file contents into an array of bytes all at once.

Reading Text Files

Let us have an example to read a simple text file using Files.readAllBytes():

try {
    // read all bytes
    byte[] bytes = Files.readAllBytes(Paths.get("input.txt"));

    // convert bytes to string
    String content = new String(bytes);
    
    // print contents
    System.out.println(content);

} catch (IOException ex) {
    ex.printStackTrace();
}

The above program will produce the following output (depending on what input.txt includes on your computer):

This
is
an
example
file.

Reading Binary Files

To read a binary file and print the contents, we need to use the Arrays.toString() method to convert it to a string:

try {
    // read all bytes
    byte[] bytes = Files.readAllBytes(Paths.get("input.dat"));

    // convert bytes to string
    String content = Arrays.toString(bytes);

    // print contents
    System.out.println(content);

} catch (IOException ex) {
    ex.printStackTrace();
}

Here is the output of the above program (again depends on contents of input.dat):

[84, 104, 105, 115, 10, 105, 115, 10, 97, 110, 10, 101, 120, 97, 109, 112, 108, 101, 10, 102, 105, 108, 101, 46]

Further Reading

You may be interested in other Java I/O articles:

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.