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