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

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Dec 7, 2019, updated Dec 11, 2019. Topics: Java.
Canonical URL: https://attacomsian.com/blog/java-files-readallbytes-example

> A short tutorial to learn how to read a file using the Files.readAllBytes() method in Java.

The `Files.readAllBytes()` static method is a part of Java's non-blocking [new I/O API](https://attacomsian.com/blog/java-read-write-files-nio-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()`:

```java
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):

```bash
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:

```java
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`):

```bash
[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:

* [Reading and Writing Files in Java](https://attacomsian.com/blog/java-read-write-files)
* [How to Read and Write Text Files in Java](https://attacomsian.com/blog/java-read-write-text-files)
* [How to Read and Write Binary Files in Java](https://attacomsian.com/blog/java-read-write-binary-files)
* [Reading and Writing Files using Java NIO API](https://attacomsian.com/blog/java-read-write-files-nio-api)
* [How to read a file line by line in Java](https://attacomsian.com/blog/how-to-read-a-file-line-by-line-in-java)
