How to use LineNumberReader to read file in java

This example show you the use of LineNumberReader class of java IO API, This class used to read the file line by line.

Below is the example of using LineNumberReader to read the file content.

package com.java.connect.io;

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

//How to use LineNumberReader to read file in java
public class LineNumberReaderExample {

	public static void main(String[] args) throws Exception {

		// Get the text file to read line by line
		File file = new File("test.txt");

		// Create FileReader object by passing the File object
		FileReader reader = new FileReader(file);
		// Get the LineNumberReadet by passing the reader object
		LineNumberReader lineReader = new LineNumberReader(reader);

		String lineContent = "";
		// Get each line and print it.
		while ((lineContent = lineReader.readLine()) != null) {
			System.out.println("Line 1 data : " + lineReader.getLineNumber()
					+ ": " + lineContent);
		}
		// Close the resources after use
		reader.close();
		lineReader.close();
	}
}

The output of the above example will be as:

Line 1 data : 1: This is example line 1
Line 1 data : 2: This is example line 2
Line 1 data : 3: This is example line 3
Line 1 data : 4: This is example line 4
Line 1 data : 5: This is example line 5
Line 1 data : 6: This is example line 6