Way2Java

Give Line Numbers LineNumberInputStream

Give Line Numbers LineNumberInputStream

Summary: By the end of this tutorial "Give Line Numbers LineNumberInputStream", you will come to know how to give line numbers using Java I/O streams.

LineNumberInputStream is a subclass of FilterInputStream stream. We know each filter stream adds some extra functionality. The LineNumberInputStream does the extra work of adding line numbers that do not exist in the source.

A program on give Line Numbers using byte stream LineNumberInputStream
import java.io.*;
public class LISDemo
{
  public static void main(String args[]) throws IOException
  {                                                                                   // reading-side
    String str1 = "The\nonly\ntrue\nwisdom\nis\nin\nknowing\nyou\nknow\nnothing\n";
    StringBufferInputStream sbstream = new StringBufferInputStream(str1);             // low-level
    LineNumberInputStream listream = new LineNumberInputStream(sbstream);             // high-level
    DataInputStream distrea m = new DataInputStream(listream);                        // high-level
					                                              // writing-side
    FileOutputStream fostream = new FileOutputStream("Quotes.txt");                   // low-level
    BufferedOutputStream bostream = new BufferedOutputStream(fostream);               // high-level
    PrintStream pstream = new PrintStream(bostream);                                  // high-level
    String str; 
    while((str = distream.readLine()) != null)
    {
      String s1 = listream.getLineNumber() + ".  " + str;
      pstream.println(s1);
      System.out.println(s1);
    }
    pstream.close();  bostream.close(); fostream.close();
    distream.close(); listream.close(); sbstream.close();
  }
}

Output screen of LISDemo.java of Give Line Numbers LineNumberInputStream

StringBufferInputStream sbstream = new StringBufferInputStream(str1); LineNumberInputStream listream = new LineNumberInputStream(sbstream);
DataInputStream distream = new DataInputStream(listream);

The above three lines are an example of I/O streams chaining. The three statements can be replaced with anonymous objects to save memory.

DataInputStream distream = new DataInputStream(new LineNumberInputStream(new StringBufferInputStream(str1)));

Similarly we can do with writing side output streams also.

listream.getLineNumber()

getLineNumber() method of LineNumberInputStream returns numbers that increments automatically. readLine() method of DataInputStream reads each line from string str1, delimited by \n, and getLineNumber() adds the line number.

When the above program is compiled, the compiler raises a warning message (see the above screen shot) as readLine() method of DataInputStream is deprecated.

A similar class on character streams is LineNumberReader which gives same functionality of adding line numbers.