Parse text file with streams in Java

8 August 2016

One of the simplest programming tasks for a java programmer is to read a text file and then parse the lines for later processing. Even if this is quite simple, I never liked it. Dealing with input streams and readers is like handling an onion. We have to take care of tons of layers even before we start to do the actual work and when we are done we have tears in our eyes. The next step is reading the file line by line and process them and when all the line are read, we need to close used resources. Closing resources was another source of problems but this was solved in Java 7 with try-with-resources statement. I prepared an example that reads a file from classpath, parses each line into an object and adds those objects into a list:

The real actual work is parsing the line from parseLine(String line) method and filling the result list, all the other code deals with file reading process. One way to improve this is using Java 8 streams: