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:
- Reading and Writing Files in Java
- How to Read and Write Text Files in Java
- How to Read and Write Binary Files in Java
- Reading and Writing Files using Java NIO API
- How to read a file line by line in Java
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.