gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 11:54:44 28 4
gpt4 key购买 nike

我一直在尝试编写一个简单的代码,我可以在其中遍历文件名列表,遍历每个文件名,并计算每个文件中有多少行。然而,下面的代码似乎根本不起作用(不断在 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com