Java中简单文件(行计数)函数的API

Java中简单文件(行计数)函数的API,java,apache,large-files,line-count,Java,Apache,Large Files,Line Count,嗨:给定一个任意文件(java),我想计算行数 这非常简单,例如,使用Apache的FileUtils.readLines(…)方法 但是,对于大型文件,就地读取整个文件是很可笑的(即,只计算行数) 一个自行开发的选项:创建BufferedReader或使用FileUtils.lineIterator函数,并计算行数 然而,我假设可能会有一个(低内存)最新的API,用于用最少的java boiler plate执行简单的大文件操作——Google、Apache等中是否存在这样的库或功能。。。开源

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

这非常简单,例如,使用Apache的FileUtils.readLines(…)方法

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

一个自行开发的选项:创建BufferedReader或使用FileUtils.lineIterator函数,并计算行数

然而,我假设可能会有一个(低内存)最新的API,用于用最少的java boiler plate执行简单的大文件操作——Google、Apache等中是否存在这样的库或功能。。。开源Java实用程序库?

包含:

int nLines=Files.readLines(文件、字符集、新行处理器(){
整数计数=0;
整数getResult(){
返回计数;
}
布尔处理行(字符串行){
计数++;
返回true;
}
});
无法将整个文件保存在内存中或任何东西。

如果没有库:

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

下面是一个使用ApacheCommons IO库的版本。您可以传递
encoding
null
,以选择平台默认值

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;
}
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++;
       }
    }
}
try(InputStream in=new BufferedInputStream(new FileInputStream(name))){
字节[]buf=新字节[4096*16];
INTC;
int lineCount=0;
而((c=in.read(buf))>0){
对于(int i=0;i

此任务中根本不需要字符串对象。

BufferedReader有什么问题?
可以获得大小,这不是比行号更好吗?不读取行号就无法计数行。另请参见LineNumberReader。是的:番石榴当然是第二好的选择-但我正在寻找一个单行解决方案。在一个文件中计算行数可能不是一个足够常见的用例,无法从番石榴那里获得自己的支持,恐怕,当我们可以支持像这样的更一般的东西时就不行了。第二种方法的一个问题是它会计算行分隔符,所以如果你有一个有一百万行的文件,它会返回999999。
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++;
       }
    }
}