LineNumberReader

In this chapter you will learn:

  1. What is LineNumberReader and how to use Java LineNumberReader

Use LineNumberReader

A buffered character-input stream that keeps track of line numbers.

LineNumberReader has setLineNumber(int) and getLineNumber() for setting and getting the current line number respectively. By default, line numbering begins at 0.

LineNumberReader defines the following constructors
  • LineNumberReader(Reader in)
    Create a new line-numbering reader, using the default input-buffer size.
  • LineNumberReader(Reader in, int sz)
    Create a new line-numbering reader, reading characters into a buffer of the given size.

LineNumberReader has the following methods:

  • int getLineNumber()
    Get the current line number.
  • void mark(int readAheadLimit)
    Mark the present position in the stream.
  • int read()
    Read a single character. The character read, or -1 if the end of the stream has been reached
  • int read(char[] cbuf, int off, int len)
    Read characters into a portion of an array. The character read, or -1 if the end of the stream has been reached
  • String readLine()
    Read a line of text.
  • void reset()
    Reset the stream to the most recent mark.
  • void setLineNumber(int lineNumber)
    Set the current line number.
  • long skip(long n)
    Skip characters.
import java.io.FileReader;
import java.io.LineNumberReader;
// ja  v a  2 s .  co  m
public class Main {
  public static void main(String[] args) throws Exception {
    LineNumberReader lnr = null;

    FileReader fr = new FileReader("c:/a.htm");
    lnr = new LineNumberReader(fr);

    String s;
    while ((s = lnr.readLine()) != null)
      System.out.println(lnr.getLineNumber() + ": " + s);
  }
}

Next chapter...

What you will learn in the next chapter:

  1. What is InputStreamReader and how to use InputStreamReader
  2. Create InputStreamReader with encoding