This post will discuss how to read the contents of a file using the Files class in Java 7.

The java.nio.file.Files class in Java provides static methods that operate on files, directories, or other types of files. The Files class was first introduced with Java SE 7. The following methods are included with Java 8 in the Files class, which are useful to read all content from a file.

1. Using Files.readAllLines(Path, Charset) method

To read all lines from a file, we can use the Files.readAllLines() method. It takes the path to the file and the charset to use for decoding from bytes to characters. It returns the lines from the file as a list and throws an IOException if an I/O error occurs reading from the stream.

Following is a simple example demonstrating the usage of this method:

Download Code

 
With Java 8, Files.readAllLines(Path, Charset) method is overloaded to accept a single parameter, which is the file’s path. The remaining usage remains the same, i.e., it returns a list that can be easily iterated.

 
Note that this method is convenient to read all lines in a single operation but strips line terminators from the end of each line. We can easily handle this by joining each of the elements of the list with a line separator, as shown below:

Download Code

2. Using Files.readAllBytes(Path) method

We can also use the readAllBytes() method, which takes the path to the file and returns a byte array containing the bytes read from the file. To get output in the string format, pass the byte array to the String constructor, as demonstrated below. The method throws an IOException if an I/O error occurs reading from the stream.

Download Code

 
To get output in the string format, pass the byte array to the String constructor with a charset for decoding.

Download Code

That’s all about reading the contents of a file using the Files class in Java.

 
Read More:

Read contents of a file in Java 8 and above

Read contents of a file in Java 11 and above