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:

We don’t have to take care anymore of reading the lines, those are provided as a stream of String instances and processing them is done declaratively with map and collect.

Your thoughts are welcome

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 reply