Keeping track of line numbers when reading a file with a Reader

Use the class filtered reader LineNumberReader. While getting the actual read buffer from the reader, you can also retrieve the current line number. You can also (re)set it with setLineNumber. This does not affect the file pointer.

This example reads in a textfile and displays a separator line every 10 lines.

Main.java:

import java.io.*;
  
public class Main {
   public static void main(String args[]) {
      if (args.length != 1) {
         System.out.println("Usage: java Main <textfile>");
         System.exit(1);
      }
  
      try {
         LineNumberReader lnr = new LineNumberReader(new FileReader(args[0]));
         String line;
         while ((line = lnr.readLine()) != null) {
            if ((lnr.getLineNumber() % 10) == 0)
               System.out.println("------------------------------------------");
            System.out.println(line);
         }
      }
      catch(IOException e) {
         System.out.println(e);
      }
   }
}