Old way of reading files sucks! Here is a better way

KonfHub
2 min readOct 18, 2019
The old-style file processing in Java sucks —instead, use new APIs with stream-style processing!

How do you read a text file in Java? If this is your answer, then its bad:

try (var inputFile = new FileReader("/Users/ganesh/limerick.txt")) {
int ch = 0;
while( (ch = inputFile.read()) != -1) {
// ch is of type int - convert it back to char
System.out.print( (char)ch );
}
}

Two problems are:

  1. It is verbose — quite a few lines of code for something as simple as reading the contents of a text file!
  2. It is low-level — like why do we have to use a int (not char, mind you!) and check with -1 for end of file and cast it back to char for printing it in console

A better way is to use the stream’s approach as in:

Files.lines(Paths.get("/Users/ganesh/limerick.txt"))
.forEach(System.out::println);

The Files.lines method reads a file and iterates over each line in the read file as a stream. The forEach consumes each string and we are printing it in the console.

This approach is much better than the earlier code because it is

  1. Concise and sweet — this code is just onto the task of reading a file, iterating over it and printing it in the console. Brief and to-the-point.
  2. High-level — easier code to read than the previous low-level code

Here is the video of writing this code in IntelliJ IDEA — hope you’ll find it useful! https://youtu.be/EIj8XD460ck

--

--

KonfHub

KonfHub is the one-stop platform to create and host tech events. Create the event in under 30 seconds, gamify & amplify for audience engagement!