Home  >  Core Java

Java LineNumberReader Example

By Arvind Rai, July 19, 2014
Java.io.LineNumberReader has been introduced in JDK 1.1. This class extends BufferedReader class. LineNumberReader keeps tracks of line number. This means while reading data, it can also provide the line number. By default LineNumberReader denotes first line as zero but we can specify a number that will be displayed using setLineNumber(int). It does not mean that LineNumberReader will start reading from specified line. It only displays incremental line number. In our example, we have given a complete demo.
LineNumberReaderDemo.java
package com.cp.io;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
public class LineNumberReaderDemo {
	public static void main(String[] args) throws IOException {
	      FileReader fr = null;
	      LineNumberReader lineNumReder = null;
	      try{
		     System.out.println("Before changing line number\n"); 
	         fr = new FileReader("D:/cp/text.txt");
	         lineNumReder = new LineNumberReader(fr);
	         String str;
	         while((str=lineNumReder.readLine())!= null){
	        	  System.out.print(lineNumReder.getLineNumber()+":");
	        	  System.out.println(str);
	         }
	         
	         System.out.println("\nAfter changing line number\n"); 
	         fr = new FileReader("D:/cp/text.txt");
	         //set line number as you want
	         lineNumReder = new LineNumberReader(fr);
	         lineNumReder.setLineNumber(10);
	         while((str=lineNumReder.readLine())!= null){
	        	  System.out.print(lineNumReder.getLineNumber()+":");
	        	  System.out.println(str);
	         }
	         
	      }catch(Exception e){
	         e.printStackTrace();
	      }finally{
	            fr.close();
	            lineNumReder.close();
	      }
	      
	   }
} 
Output is given as below.
Before changing line number

1:Hello World!
2:This is LineNumberReader Program.
3:Happy Learning.

After changing line number

11:Hello World!
12:This is LineNumberReader Program.
13:Happy Learning.
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us