下面是来自Java 中文件中的行数的解决方案, 用于快速计算文本文件中的行数。
但是,我正在尝试编写一种方法来执行相同的任务而不会引发“IOException”。
在最初的解决方案下,我尝试使用嵌套的 try-catch 块 <-- (这通常是完成/皱眉/或容易避免吗??)无论给定文件中有多少行,它都会返回 0(显然失败)。
为了清楚起见,我并不是在寻找有关如何更好地使用包含异常的原始方法的建议,因此,我使用它的上下文与这个问题无关。
有人可以帮我写一个方法来计算文本文件中的行数并且不会抛出任何异常吗?(换句话说,用 try-catch 处理潜在的错误。)
martinus的原始行计数器:
public static int countLines(String filename) throws IOException {
InputStream is = new BufferedInputStream(new FileInputStream(filename));
try {
byte[] c = new byte[1024];
int count = 0;
int readChars = 0;
boolean empty = true;
while ((readChars = is.read(c)) != -1) {
empty = false;
for (int i = 0; i < readChars; ++i) {
if (c[i] == '\n') {
++count;
}
}
}
return (count == 0 && !empty) ? 1 : count;
} finally {
is.close();
}
}
我的尝试:
public int countLines(String fileName ) {
InputStream input = null;
try{
try{
input = new BufferedInputStream(new FileInputStream(fileName));
byte[] count = new byte[1024];
int lines = 0;
int forChar;
boolean empty = true;
while((forChar = input.read(count)) != -1){
empty = false;
for(int x = 0; x < forChar; x++){
if(count[x] == '\n'){
lines++;
}
}
}
return (!empty && lines == 0) ? 1 : lines + 1;
}
finally{
if(input != null)
input.close();
}
}
catch(IOException f){
int lines = 0;
return lines;
}
}