How to Count Lines for Files in Java

Asked 2 years ago, Updated 2 years ago, 37 views

There's a huge data file. Sometimes you need to know how many lines of these data files are Until now, I've been reading this line by line, but I wonder if there's a way to read it more efficiently.

java large-files line-numbers

2022-09-21 21:53

1 Answers

When tested, it is 6 times faster than readLine. If it is a 150 megabyte log file, it will read in 0.35 seconds. It takes 2.40 seconds to readLines().

public static int countLines(String filename) throws IOException {
    InputStream is = new BufferedInputStream(new FileInputStream(filename));
    try {
        byte[] c = new byte[1024];
        int count = 0;
        int readChars = 0;
        boolean empty = true;
        while ((readChars = is.read(c)) != -1) {
            empty = false;
            for (int i = 0; i < readChars; ++i) {
                if (c[i] == '\n') {
                    ++count;
                }
            }
        }
        return (count == 0 && !empty) ? 1 : count;
    } } finally {
        is.close();
    }
}


2022-09-21 21:53

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.