Java - LineNumberReader example

Posted on November 8, 2016


LineNumberReader is a buffered character-input stream that keeps track of line numbers. It is a subclass of the BufferedReader, which provides additional methods setLineNumber() and getLineNumber() for setting and getting the current line number respectively.

Here is an example to demonstrate this.

A sample input file for LineNumberReaderExample.java.

file.txt

Hello Friends!
This is an example of LineNumberReader
LineNumberReader is a subclass of BufferedReader

LineNumberReaderExample.java

package com.boraji.tutorial.io;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;

/**
 * @author imssbora
 */
public class LineNumberReaderExample {
	public static void main(String[] args) {
		File file = new File("file.txt");
		FileReader fileReader = null;
		LineNumberReader lineNumberReader = null;
		try {
			fileReader = new FileReader(file);
			lineNumberReader = new LineNumberReader(fileReader);
			
			//Get Line number
			int lineNum=lineNumberReader.getLineNumber();
			System.out.println("Line number : "+lineNum);
			
			//Set line number
			lineNumberReader.setLineNumber(2);
			
			//Get Line Number
			lineNum=lineNumberReader.getLineNumber();
			System.out.println("Line number : "+lineNum);
			
			String line=null;
			while((line=lineNumberReader.readLine())!=null){
				System.out.println(line);
			}
			
			//Get Line Number
			lineNum=lineNumberReader.getLineNumber();
			System.out.println("Line number : "+lineNum);
			
			
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				if(fileReader!=null){
					fileReader.close();
				}
				if(lineNumberReader!=null){
					lineNumberReader.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}

Output

Line number : 0
Line number : 2
Hello Friends!
This is an example of LineNumberReader
LineNumberReader is a subclass of BufferedReader
Line number : 5