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 {
       FileReader fr = new FileReader(args[i]);
       LineNumberReader br = new LineNumberReader(fr);
       while ((thisLine = br.readLine()) != null) { 
         System.out.println(br.getLineNumber() + ": " + thisLine);
       } // end while 
     } // end try
     catch (IOException ex) {
       System.err.println("Error: " + ex);
     }
  } // end for
  
} // end main

}

Previous | Next | Top | Cafe au Lait

Copyright 1997, 2006 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified September 18, 2006