How to read a file in Java Posted in Polyglotbits on 13 of Sep, 2016

Java is - off course you might joke - rather verbose when it comes to reading files. However most of the verbosity has to do with importing the functionality from the standard library.

We need three things imported, Files, Paths and then the IOException that may get thrown.

import java.nio.file.Files;
import java.nio.file.Paths;
class Test {
  public static void main (String[] args) {
    int i = 0;
    try {
    for (String line : Files.readAllLines(Paths.get(args[0]))) {
      System.out.println(Integer.toString(i) + " " + line);
    } catch (IOException ex) {

Java forces us to handle the exception that might get thrown, so we import the exception type, and wrap our example code in a try/catch block that handles that Exception (by doing nothing: don’t do this in production).

The example then is rather simple. We use Paths.get to convert the first program argument to a path object, that can be sent to Files.readAllLines - which does exactly what it says on the box: return all lines of the input file, as a List<> of strings.

We then iterate over this list, printing it to stdout prefixed by a line number.

More about Java