Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 781
jayunit100 Avatar asked Dec 28 '22 04:12

jayunit100


1 Answers

With Guava:

int nLines = Files.readLines(file, charset, new LineProcessor<Integer>() {
  int count = 0;
  Integer getResult() {
    return count;
  }
  boolean processLine(String line) {
    count++;
    return true;
  }
});

which won't hold the whole file in memory or anything.

like image 126
Louis Wasserman Avatar answered Jan 13 '23 21:01

Louis Wasserman