Read all lines of the file using Files.readAllLines method

1. readAllLines method

Method signature

public static 
List<String> readAllLines(Path path) throws IOException

readAllLines method is an overloaded method in Files class. Let’s first see the method version that added prior to Java 8. readAllLines(Path path, Charset cs) was added prior to Java 8 can be used as follows:

import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
 
List<String> fileData = Files.readAllLines(
                            Paths.get("words.txt"), 
                            StandardCharsets.UTF_8);

In the newer version of readAllLines i.e. method added in Java 8, it does not have the Charset parameter.

readAllLines(Path path) method works same as invoking 

readAllLines(Path path, StandardCharsets.UTF_8)

import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
 
List<String> fileData = Files.readAllLines(Paths.get("words.txt"));

readAllLines method reads all the lines of the file, inserts those lines in List and returns the List. This method can throw IOException if a malformed or unmapped byte sequence is read or some I/O error occurs while reading the file.

2. Conclusion

readAllLines method is overloaded utility method of Files class. In this article we saw two different variants of readAllLines. readAllLines(Path, Charset) was added prior to Java 8 and readAllLines(Path) was added in Java 8. Both the methods perform the exact same task i.e. reading the lines of a file, inserting those lines in List and returning the List. readAllLines(Path path) method works the same as invoking readAllLines(Path path, Charset charset).

readAllLines is not lazy method i.e. as soon as the method is called it will load the lines of file into List. As of Java 8 a new method called lines(Path) and lines(Path, Charset) is added. This methods return Stream<String> and the lines are populated from file lazily i.e. when the stream is consumed. We will look at these methods in the next article.

Leave a Reply

Your email address will not be published. Required fields are marked *