This post will discuss how to read the contents of a file in Java.

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, and several new utility methods were added to it with Java 8. 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.lines(Path) method

The Files.lines(Path) method can be used to read all lines from a file as a stream. It accepts the path to the source file and returns the lines from the file as a stream. The decoding from bytes to characters is done using the UTF-8 charset, i.e., this method is equivalent to: Files.lines(path, StandardCharsets.UTF_8). It throws an IOException if an I/O error occurs while opening the file.

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

Download Code

 
Note that the Files.lines() method doesn’t include line-termination characters. If we want to read all text from a file into a string in Java, we can do something like:

Download Code

2. Using Files.lines(Path, Charset) method

Files.lines(Path, Charset) method can be used to read all lines from a file as a stream using the specified charset to decode bytes to characters.

It takes the path to the file and the charset used for decoding as parameters. It returns the lines from the file as a stream and throws an IOException if an I/O error occurs while opening the file. Following is a simple example demonstrating the usage of this method:

Download Code

3. Using BufferedReader.lines() method

Java 8 also introduced the BufferedReader.lines() method, which returns a stream of lines of text read from BufferedReader. This is demonstrated below using Stream:

Download Code

 
Similar to the Files.lines() method, the BufferedReader.lines() method doesn’t include line-termination characters. If we want to read all text from a file into a string in Java, we can use Java 8 Stream collect() method, as demonstrated earlier.

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

 
Read More:

Read all text from a file into a String in Java