LineNumberReader in Java

A buffered character-input stream that keeps track of line numbers.

LineNumberReader extends BufferedReader. Line numbering begins at 0. Whenever the LineNumberReader encounters a line terminator in the characters returned by the wrapped Reader, the line number is incremented.

You can get the current line number from the LineNumberReader by calling the getLineNumber() method. You can also set the current line number by calling the setLineNumber() method.

Constructors

Screen Shot 2020-04-05 at 10.58.55 AM

Methods

LineNumberReader in Java

package com.java.io;

import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;

public class LineNumberReaderExample {

    public static void main(String[] args) {

        FileReader fileReader = null;
        LineNumberReader lineNumberReader = null;
        try {
            fileReader = new FileReader("/Test/TestFolder/test-file1.txt");
            lineNumberReader = new LineNumberReader(fileReader);
            String line = lineNumberReader.readLine();
            while (line != null) { 
                int lineNumber = lineNumberReader.getLineNumber(); 
                System.out.println("line" + lineNumber + "->" + line); 
                line = lineNumberReader.readLine(); 
            }

        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (fileReader != null)
                try {
                    fileReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            if (lineNumberReader != null)
                try {
                    lineNumberReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }

    }

}
line1->Test data1
line2->Test data2
line3->Test data3

Related Article

Java I/O Basics

Leave a Reply

Your email address will not be published. Required fields are marked *