Java developers, reading text from a file is not a thing anymore!

Suppose you have to read the contents of a text file. This is a commonly recurring task. If you think about the amount of code required in Java or have the experience of already implementing it, you would agree with me that it takes a significant amount of code.

Following is a typical code example of reading a text file in Java.

Path source = Paths.get("/Users/naresha/temp/names.txt");
final StringBuilder stringBuilder = new StringBuilder();
try (BufferedReader bufferedReader = Files.newBufferedReader(source)) {
    String line = bufferedReader.readLine();
    while (line != null) {
        stringBuilder.append(line).append(System.lineSeparator());
        line = bufferedReader.readLine();
    }
} catch (IOException e) {
    e.printStackTrace();
}
System.out.println(stringBuilder.toString());

We took advantage of the automatic resource management feature introduced in Java 7, which overcomes complexities involved with closing a resource.

I have seen this code sitting in a util class in most of the projects I worked with. Alternatively, some teams preferred including Apache Commons IO library.

Fortunately, you don't have to write that many lines of code if you are using Java 11 and above. Java 11 introduces readString() method which can read the entire content of a text file.

Path source = Paths.get("/Users/naresha/temp/names.txt");
try {
    final String text = Files.readString(source);
    System.out.println(text);
} catch (IOException e) {
    e.printStackTrace();
}

readString takes care of opening an IO stream and closing it after a successful read or an exception, which is quite useful. The only thing that bothers me here is the method throws a checked exception, which adds some noise to the code. However, I understand that it was not easily avoidable due to the objective of achieving consistency of APIs overrules. The only option was to introduce another level of runtime exception.

There is also readAllLines() method which returns a List of String where each item corresponds to a line from the input file.

Path source = Paths.get("/Users/naresha/temp/names.txt");
try {
    final List<String> lines = Files.readAllLines(source);
    System.out.println(lines);
} catch (IOException e) {
    e.printStackTrace();
}