How do I use LineNumberReader class to read file?

In this example we use LineNumberReader class to read file contents. What we try to do here is to get the line number of the read data. Instead of introducing another variable; an integer for instance; to keep track the line number we can utilize the LineNumberReader class. This class offers the getLineNumber() method to know the current line of the data that is read.



public class LineNumberReaderExample {
    public static void main(String[] args) throws Exception {
        FileReader fr = null;
        LineNumberReader lnr = null;

        try {
            // We'll read a file called student.csv that contains our
            // student information data.
            URI uri = LineNumberReaderExample.class
            File file = new File(uri);

            // To create the FileReader we can pass in our student data
            // file to the reader. Next we pass the reader into our 
            // LineNumberReader class.
            fr = new FileReader(file);
            lnr = new LineNumberReader(fr);

            // If we set the line number of the LineNumberReader here
            // we'll got the line number start from the defined line 
            // number + 1


            String line;
            while ((line = lnr.readLine()) != null) {
                // We print out the student data and show what line
                // is currently read by our program.
                System.out.println("Line Number " + lnr.getLineNumber() +
                        ": " + line);
        } finally {
            // Don't forget to close the stream when we finish reading
            // the file.
            if (fr != null) {
            if (lnr != null) {

The /resources/student.csv file:

Alice, 7
Bob, 8
Carol, 5
Doe, 6
Earl, 6
Malory, 8

And here is the result of our code snippet above:

Line Number 1: Alice, 7
Line Number 2: Bob, 8
Line Number 3: Carol, 5
Line Number 4: Doe, 6
Line Number 5: Earl, 6
Line Number 6: Malory, 8

Wayan Saryada

Programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply