Iterating over the lines of a file in Java

If you’re trying to write a standard command-line tool in Java you are going to experience pain.

In Python, if we want to do something with each line on input to your program, we can do something like:

import sys
for ln in sys.stdin:
    print(ln)  # (We have an extra newline but who's counting?)

In Java, after some fighting, the two closest alternatives I can find are:

import java.util.Scanner;
class IterateInputScanner {
    public static void main(String[] args) {
        for(String ln : (Iterable)(() -> new Scanner("\n"))) {

or, less fashionably, and even more horribly:

class IterateInputReader {
    public static void main(String[] args) throws {
        BufferedReader reader =
            new BufferedReader(new InputStreamReader(;
        String ln;
        while((ln = reader.readLine()) != null) {

Note that if you are reading from a stream other than stdin you will probably want to wrap this in a try-with-resources to close the stream when you’ve finished.

Take your pick, and I hope it saves you some fighting.

2 thoughts on “Iterating over the lines of a file in Java”

  1. Check out java.nio.file.Files and java.nio.file.Paths. Something like:

    Files.lines(Paths.get(fileToRead)).forEach((line) -> {
    } );

Leave a Reply

Your email address will not be published. Required fields are marked *

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