Wednesday, 23 July 2014

Java program that reads a file and displays a file on the screen with a line number before each line

Program

import java.lang.*;
import java.io.*;
class linenum
{
  public static void main(String args[])
  {
      int i;
      FileInputStream f;
      LineNumberInputStream l;
      try
      {
        f=new FileInputStream(args[0]);
        l=new LineNumberInputStream(f);
      }
      catch(FileNotFoundException e)
      {
        System.out.println("No such file");
        return;
      }
     do
     {
       i=l.read();
       if(i=='\n')
       {
         System.out.println();
         System.out.print(l.getLineNumber()+" ");
       }
       else
       {
         System.out.print((char)i);
       }
     }while(i!=-1);

     f.close();
     l.close();
  }
}



No comments:

Post a Comment