Java file LineNumberReader


 

Java file LineNumberReader

This section illustrates you the use of class LineNumberReader.

This section illustrates you the use of class LineNumberReader.

Java file LineNumberReader

This section illustrates you the use of class LineNumberReader.

It is a buffered character-input stream that keeps track of line numbers of the file. This class defines methods for setting and getting the current line number.

Now to read a file and display its line number, we have used FileReader class. Then we have passed the FileReader object to the LineNumberReader class. We have utilized the LineNumberReader class to keep track the line number. This class offers the getLineNumber() method to get the current line of the data that is read.

getLineNumber(): This method of class LineNumberReader returns the current line number.

Here is the file.txt:

Hello World

All glitters are not gold.
Truth is better than facts.
A man is not old until regrets take the place of dreams.

Here is the code:

import java.io.*;

public class FileLineNumberReader {
	public static void main(String[] args) throws Exception {
		File file = new File("C:/file.txt");
		FileReader reader = new FileReader(file);
		LineNumberReader linereader = new LineNumberReader(reader);
		String line = "";
		while ((line = linereader.readLine()) != null) {
			System.out.println("Line Number " + linereader.getLineNumber()
					+ ": " + line);
		}
		reader.close();
		linereader.close();
	}
}

Output:

Line Number 1: Hello World
Line Number 2:
Line Number 3: All glitters are not gold.
Line Number 4: Truth is better than facts.
Line Number 5: A man is not old until regrets take the place of dreams.

Ads