Count total number of lines of a file in Java

 Posted On  | Yashwant Chavan 

One of my friend requested me sample code to find out the Total number of lines of the input file using java. So I had implemented the sample code which reads the input file line by line and increment the counter accordingly.

But he was not happy with the solution, because for extra large file it took significant amount of time to calculate the total number of lines. So I modified my line counter program which get the total line in efficient way.

Line Counter Code Snippet

BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
int lines = 0;
while (reader.readLine() != null) {
    lines++;
}
reader.close();

LineNumberReaderTest.java

Modified code is faster than above code snippet. LineNumberReader class used to create a new line-numbering reader, using the default input-buffer size. skip method is used to skip the n number characters.

So we skip the Long.MAX_VALUE number characters(A constant holding the maximum value a long can have 9223372036854775807 [0x7fffffffffffffff]). And getLineNumber() method return the current line number which is last one.

package com.technicalkeeda;

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

public class LineNumberReaderTest {
    public static void main(String[] args) {
        int totalLines = new LineNumberReaderTest().countLineNumber();
        System.out.println("Total Number Lines " + totalLines);
    }

    public int countLineNumber() {
        int lines = 0;

        try {

            File file = new File("file.txt");
            LineNumberReader lineNumberReader = new LineNumberReader(new FileReader(file));
            lineNumberReader.skip(Long.MAX_VALUE);
            lines = lineNumberReader.getLineNumber();
            lineNumberReader.close();

        } catch (FileNotFoundException e) {
            System.out.println("FileNotFoundException Occurred" + e.getMessage());
        } catch (IOException e) {
            System.out.println("IOException Occurred" + e.getMessage());
        }

        return lines;
    }
}

output

Compile and Run LineNumberReaderTest.java

Total Number Lines 189280


© technicalkeeda.com 2017

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0298 seconds.