4

嗨:给定一个任意文件(java),我想计算行数。

这很容易,例如,使用 Apache 的 FileUtils.readLines(...) 方法...

然而,对于大文件,就地读取整个文件是可笑的(即只计算行数)。

一个本土选项:创建 BufferedReader 或使用 FileUtils.lineIterator 函数,并计算行数。

但是,我假设可能有一个(低内存),最新的 API 用于执行简单的大型文件操作,而 Java 的样板数量最少——任何此类库或功能是否存在于任何Google、Apache 等...开源 Java 实用程序库?

4

4 回答 4

6

番石榴

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

它不会将整个文件保存在内存或任何东西中。

于 2012-03-13T20:21:11.667 回答
3

Java 8 捷径:

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

但大多数内存效率:

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++;
       }
    }
}

在此任务中您根本不需要 String 对象。

于 2015-10-12T16:24:21.393 回答
1

没有图书馆:

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;
}
于 2012-03-13T20:28:51.173 回答
0

这是一个使用 Apache Commons IO 库的版本。您可以通过nullforencoding选择平台默认值。

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;
}
于 2013-11-14T17:43:25.010 回答