java - 遍历文件列表以检查里面有多少行

标签 java inputstream

我一直在尝试编写一个简单的代码,我可以在其中遍历文件名列表,遍历每个文件名,并计算每个文件中有多少行。 然而,下面的代码似乎根本不起作用(不断在 Eclipse 中启动调试透视图)。

public class fileScanner {

public static void main(String[] args) throws IOException {
    ArrayList<String> list = new ArrayList<String>();
    //add files
    list.add("C:\\Users\\HuiHui\\Documents\\eclipse\\test.txt");
    for (String l : list){
        fileScan(l);
    }

}

public static int fileScan(String filename) throws IOException {
    InputStream is = new BufferedInputStream(new FileInputStream(filename));
    try {
        byte[] c = new byte[1024];
        int count = 0;
        int readChars = 0;
        boolean endsWithoutNewLine = false;
        while ((readChars = is.read(c)) != -1) {
            for (int i = 0; i < readChars; ++i) {
                if (c[i] == '\n')
                    ++count;
            }
            endsWithoutNewLine = (c[readChars - 1] != '\n');
        }
        if(endsWithoutNewLine) {
            ++count;
        } 
        return count;
    } finally {
        is.close();
    }
}

}

有人能解释一下吗?

最佳答案

您使用 InputStream 并创建 BufferedInputStream 而不是使用 BufferedReader 来完成这项工作是否有原因?

尝试使用您的filescan方法

int filescan(String filename) throws IOException {
   BufferedReader br = new BufferedReader(new FileReader(filename));
   int count=0;
   String s;
   while((s=br.nextLine()) != null) 
       count++;
   br.close();
   return count;
}

关于java - 遍历文件列表以检查里面有多少行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28533435/

相关文章:

java - 处理除 MessagingException 以外的异常/错误,即..,在 spring-integration 中未包装为 MessagingException 的其他错误/异常

java - 是否可以在不关闭流的情况下关闭阅读器?

java - InputStream - 处理网络变化

java - 将输入流转换为位图

java - mvc架构会影响SEO吗?

java - Robolectric、Maven 和输出文件夹的困境

java - 制作文件输入流时未找到文件异常?

java - 将输入流转换为位图

Java - 无法将我的 MySQL JAR 文件添加到 Eclipse 的构建路径中

java - 如何将 'unsafe' 参数传递给 Java Webstart 应用程序的 JVM