Friday, March 18, 2011

How to add line number to text file ?

The following sample shows how to add line number to a text file.
You may change the input filename "LineNumberAdder.java" in line 12.

Create output file by issuing the following command :
java LineNumberAdder >output.txt 


/******************************************************************************
* File : LineNumberAdder.java
* Author : http://java.macteki.com/
* Description :
*   Display the contents (with line number) of a text file.
******************************************************************************/

public class LineNumberAdder
{
  public static void main(String[] args) throws Exception
  {
    String inputFileName="LineNumberAdder.java";
    java.io.BufferedReader br=new java.io.BufferedReader(
      new java.io.FileReader(inputFileName));
   
    String line=null;
    int lineNum=0;
    while ((line=br.readLine())!=null)     
    {
      lineNum++;
      System.out.println(lineNum+"\t"+line);
    }
  }
}

No comments:

Post a Comment