How to read a file in Java

Tue, Sep 13, 2016

Read in 1 minutes

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.io.IOException;
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]))) {
      i++;
      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.

See Also

How to Read a File in C#

Tue, Nov 8, 2016

Read more →

How to Read a File in Lua

Fri, Oct 28, 2016

Read more →

How to Read a File in C++

Tue, Oct 4, 2016

Read more →

How to Read a file in JavaScript

Fri, Nov 27, 2015

Read more →

How to Read a file in Go

Thu, Nov 26, 2015

Read more →