API for simple File functions (row count) in Java

Hey. For an arbitrary file (java) I want to count lines.

It is quite simple, for example, using the Apache FileUtils.readLines (...) method ...

However, for large files, reading the whole file in place is ridiculous (i.e. just for line counting).

One homegrown option: create a BufferedReader or use the FileUtils.lineIterator function and count the lines.

However, I assume that there may exist (with low memory) a modern API for performing simple large file operations with a minimal amount of boiler plate for java. Does any such library or functionality exist anywhere in any of Google, Apache, etc ... open source Java utilities?

+4
source share
4 answers

Java 8:

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

But most memory features:

 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.

+2
source

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 will not contain the entire file in memory or anything else.

+6
source

Without library:

 public static int countLines(String filename) throws IOException { int count = 0; BufferedReader br = new BufferedReader(new FileReader(filename)); try { while (br.readLine() != null) count++; } finally { br.close(); } return count; } 
+1
source

Here is the version using the IO Apache Commons library. You can pass null for encoding to select the default platform.

 import org.apache.commons.io.FileUtils; import org.apache.commons.io.LineIterator; public static long countLines(String filePath, String encoding) throws IOException { File file = new File(filePath); LineIterator lineIterator = FileUtils.lineIterator(file, encoding); long lines = 0; try { while ( lineIterator.hasNext() ) { lines++; lineIterator.nextLine(); } } finally { LineIterator.closeQuietly( lineIterator ); } return lines; } 
0
source

Source: https://habr.com/ru/post/1401245/


All Articles