Search code examples
javaapachelarge-filesline-count

API for simple File (line count) functions in Java


Hi : Given an arbitrary file (java), I want to count the lines.

This is easy enough, for example, using Apache's FileUtils.readLines(...) method...

However, for large files, reading a whole file in place is ludicrous (i.e. just to count lines).

One home-grown option : Create BufferedReader or use the FileUtils.lineIterator function, and count the lines.

However, I'm assuming there could be a (low memory), up to date API for doing simple large File operations with a minimal amount of boiler plate for java --- Does any such library or functionality exist anywhere in the any of the Google, Apache, etc... open-source Java utility libraries ?


Solution

  • Java 8 short way:

     Files.lines(Paths.get(fileName)).count();
    

    But most memory effiecint:

    try(InputStream in = new BufferedInputStream(new FileInputStream(name))){
        byte[] buf = new byte[4096 * 16];
        int c;
        int lineCount = 0;
        while ((c = in.read(buf)) > 0) {
           for (int i = 0; i < c; i++) {
               if (buf[i] == '\n') lineCount++;
           }
        }
    }
    

    You do not need String objects in this task at all.