LineNumberReader class

 

see  Reader class  for descriptions of LineNumberReader's inherited methods.  They are:

 

.mark( readAheadLimit )  Mark the present position in the stream.

.markSupported( ) Tell whether this stream supports the mark(...) operation.

.read( )  Read a single character, returning it in the low end two bytes of an int.

.read( char[ ] )  Read characters into a char array.

.read( char[ ], offset, len)  Read characters into a portion of a char array.

.ready( ) Tell whether this stream is ready to be read.

.reset( )  Reset the stream.

.skip( n )  Skip over n characters in the stream.

.close( ) Close the stream.

 

plus

 

.readLine( )   in  BufferedReader 

 

and

 

.getLineNumber( )  

.setLineNumber( )           below

 

 

  LineNumberReader extends BufferedReader, adding two methods, getLineNumber( ) and setLineNumber( ).  It is normally used with the inherited readLine( ) method from its parent BufferedReader.

 

 

int  .getLineNumber( )  method

 

  This method, which does not perform any I/O, returns an int indicating the last line number which was read (using readLine( )) from a LineNumberReader stream object.  Zero will be returned if no read operations have as yet occurred

 

  You cannot obtain line numbers if you try to read the stream using a BufferedReader object.  Such references to getLineNumber( ), which is a LineNumberReader method, will not compile.

 

  LineNumberReader supports mark(...) and reset( ).

 

  Printing numbered file lines.   This LineNumberReader snippet uses getLineNumber( )  to obtain each incoming line number and then print it in front of its line.  Note that this concentrates on the lines, not individual characters.  It will work best if pointed at a byte file.  In a UTF-16 file, the extra length of line-ending characters will make it think there are extra lines present.

 

import java.io.*;

 

try {

LineNumberReader lnr = new LineNumberReader(new FileReader("myfile"));

String s;

    while ( (s = lnr.readLine( )) != null  )  {

          System.out.println( lnr.getLineNumber( ) + ": " + s );

    }

}

catch(Exception ex) { }

 

 

void  .setLineNumber( lineno )  method

 

  This method allows you to control what int line numbers are returned by getLineNumber( ).

 

  You cannot use this method to influence which line is read.  It just resets the starting logical line number which getLineNumber( ) will use next. i.e. The setLineNumber( ) statement below means subsequent printed line numbers will start at 100, 101, etc.  It doesn't make readLine( ) actually jump to the 100th record.

 

import java.io.*;

 

try {

LineNumberReader lnr = new LineNumberReader(new FileReader("myfile"));

String s;

lnr.setLineNumber( 100 );

while ( (s = lnr.readLine( )) != null  )  {

      System.out.println( lnr.getLineNumber( ) + ": " + s );

}

}

catch(Exception ex) { }