Death by boilerplate: Iterating over lines in a file in Java (vs Scala, Ruby, Groovy)

| June 18, 2012

This post comes to us from the Code General. It's a good read and points to some issues that we hope to see resolved when JDK 8 is rolled out.

How to iterate over lines in a file in Java, Scala, Ruby and Groovy

Iterating over the lines of a small text file is a pretty common (and simple) operation. Given how routine this task is you would think that it would require minimal code. Java is quite famous for requiring lots of code to get the job done. Using the standard libraries in Java 6 we typically end up with code looking something like this:

Java 6:

Every Java programmer has at one stage or another had to write code that looks a lot like this. I’ve probably written code looking a lot like this many, many times. Even for someone who can type very quickly it’s a lot of boilerplate. It’s not particularly complicated code, just very verbose. While there are 3rd party libraries (Apache commons,io) that make this much simpler many (most?) developers will rather just use the standard libs.

This may seem perfectly reasonable to a seasoned Java dev, but for anyone coming from Python, Ruby or even C# the amount of code required for this simple task seems excessive. Java 7 improves on this somewhat with ARM (Automatic Resource Management) and by providing utility methods in java.nio.file.Files. I was originally going to write a blog post about how useful this class is for doing file reads with minimal boilerplate code, but alas it still requires some extra plumbing. The readAllLines(Path path, Charset cs) method cuts down on much of the boilerplate. Unfortunately it still requires a path object to be created, along with a charset (no option to use the default on the local system). This results in code along these lines:

Java 7:

If we compare this with virtually any well known modern language the difference is obvious. Consider for example the code required to perform this tasks in Scala, Ruby or Groovy:




Notice how much less boilerplate is involved. It only takes one line of code to perform the task. The question which needs to be asked is this: after more than 15 years, reading from a file in Java is still more painful than virtually any other modern language. This would be easy to fix by providing sensible methods with defaults. Imagine something more like:

Please Oracle, add something sensible like this to JDK 8.