LineNumberReader Java


The character stream LineNumberReader is equivalent to LineNumberInputStream on byte streams side. Being a subclass of BufferedReader, it can make use of all the methods of BufferedReader like readLine() to read a line. getLineNumber() method of this class can be used to give line numbers.

Following is the class signature of LineNumberReader Java:

public class LineNumberReader extends BufferedReader

Giving Line Numbers

The functionality of LineNumberReader is to give line numbers that do not exist in the source file.

File Name: Cities.txt (this file is used in the next program)

Capital city: Delhi
Financial capital: Mumbai
Software jungle: Bengaluru
Pink city: Jaipur
Cyber city: Hyderabad (Cyberabad)

The above file is read by the following program and prints the lines along numbers.

import java.io.*;
public class LNRDemo
{
  public static void main(String args[]) throws IOException
  {
    FileReader freader = new FileReader("Cities.txt");
    LineNumberReader lnreader = new LineNumberReader(freader);

    String s1;
    while((s1 = lnreader.readLine()) != null)
    {
      System.out.println(lnreader.getLineNumber() + ": " + s1);
    }
    lnreader.close();  
    freader.close();
   }
}

LineNumberReader Java
Output screenshot on LineNumberReader Java

FileReader freader = new FileReader(&quot:Cities.txt&quot:);
LineNumberReader lnreader = new LineNumberReader(freader);

The file Cities.txt is passed to the constructor of FileReader to open in read-mode. The FileReader object freader is chained to LineNumberReader. The LineNumberReader includes a special method getLineNumber() capable to give line numbers that increments automatically.

Leave a Comment

Your email address will not be published.