How to read a text file line by line with Java NIO

I want to show you how to read all the lines of a file with the Java Non-blocking I/O API (package java.nio) and provide some historical context how this compares to earlier versions of the API.

Back in the days

Before Java version 1.7 there was the package and the basic building block was its class File. You could create File instances and had access to a lot of different operations like checking whether the given pathname exists, whether it is a directory or a regular file and you could create, rename or delete the file and also list the child files if you had a directory in your hands.

If you wanted to read from a file you could construct an InputStream or a Reader and could choose from different implementations to read the data from the filesystem. This may consist of some loop – a while loop for example – and reading chunks of bytes into some sort of buffer so you could work on that later. For beginners most of the time this was not very easy to understand. With java.nio all this should be easier to handle.

Read all lines from a file

The counterpart to the File class is the Path interface in java.nio.file. Basically it is just a wrapper to hold a file path in a file system. Instead of directly constructing Path instances you can use the Paths helper class also from java.nio.file.

If you want to do all different kinds of operations in the file system you can use the Files class also located in java.nio.file. Have a look at all the different methods of that class if you want to but for now we will focus on the readAllLines method.

Path path = Paths.get("test-file.txt");
Charset charset = StandardCharsets.UTF_8;
List<String> lines = Files.readAllLines(path, charset);

You supply a Path instance and a charset – that you can obtain from the class StandardCharsets located in java.nio.charset – and the method simply returns an ArrayList holding all the lines of the file as Strings. There is no need to come up with some sort of loop or to close open streams or reader instances but just this method call.

You can then continue to work with the individual lines of the file and for example use the Java Streaming API to map to something else.