Line Numbering

The java.io.LineNumberReader class is a subclass of java.io.BufferedReader that keeps track of which line you're currently reading. It has all the methods of BufferedReader including readLine(). It also has two constructors, getLineNumber(), and setLineNumber() methods:

 public LineNumberReader(Reader in)
 public LineNumberReader(Reader in, int size)
 public void setLineNumber(int lineNumber)
 public int getLineNumber()
The setLineNumber() method does not change the file pointer. It just changes the value getLineNumber() returns. For example, it would allow you to start counting from -5 if you knew there were six lines of header data you didn't want to count.

The following example reads a text file, line by line, and prints it to System.out but prefixes each line with a line number:

import java.io.*;

class linecat  {

  public static void main (String args[]) {
  
    String thisLine;
 
   //Loop across the arguments
   for (int i=0; i < args.length; i++) {
 
     //Open the file for reading
     try {
       LineNumberReader br = new LineNumberReader(new FileReader(args[i]));
       while ((thisLine = br.readLine()) != null) { // while loop begins here
         System.out.println(br.getLineNumber() + ": " + thisLine);
       } // end while 
     } // end try
     catch (IOException e) {
       System.err.println("Error: " + e);
     }
  } // end for
  
} // end main

}

Previous | Next | Top
Last Modified June 16, 1997
Copyright 1997 Elliotte Rusty Harold
elharo@metalab.unc.edu