Java LineNumberReader Example

In my previous example I have explained about the BufferedReader for reading the huge amount of data and parse it line by line. LineNumberReader is the specialized version of the BufferedReader where this class can store the line number in the file when it reads from the file. It is very useful when there is any error occurred, we can print the line number to look at the file for the problem. The following are the few methods which are very useful.

  • setLineNumber(int) – You can set the line number from where you want to read the text file. This actually sets the line number to be printed.
  • getLineNumber () – You can get the current line number in the loop

Other methods are similar to the one inherited from the BufferedReader class. Lets look at the example to understand how to use the LineNumberReader.

LineNumberReader Example

LineNumberReaderExample.java

package javabeat.net.core;

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

/**
 * File LineNumberReader Example
 *
 * @author Krishna
 *
 */
public class LineNumberReaderExample {
	public static void main(String args[]) {
		FileReader fileReader = null;
		LineNumberReader lineNumberReader = null;
		String str = null;
		try {
			fileReader = new FileReader("TextFile.txt");
			lineNumberReader = new LineNumberReader(fileReader);

			//Setting the line number
			lineNumberReader.setLineNumber(3);
			while ((str = lineNumberReader.readLine()) != null) {
				System.out.print("Line Number ::"+lineNumberReader.getLineNumber()+":: ");
				System.out.println(str);
			}
			lineNumberReader.close();
		} catch (FileNotFoundException exception) {
			exception.printStackTrace();
		} catch (IOException exception) {
			exception.printStackTrace();
		}
	}
}

TextFile.txt

Reading
the
text
content
using LineNumberReader!!

Output…

Line Number ::4:: Reading
Line Number ::5:: the
Line Number ::6:: text
Line Number ::7:: content
Line Number ::8:: using LineNumberReader!!

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*