如果我读取的文件段落之间有空格,我如何计算空格并从总行数中减去它们?
public int countLinesInFile(File f){
int lines = 0;
try {
BufferedReader reader = new BufferedReader(new FileReader(f));
while (reader.readLine() != null){
lines++;
}
reader.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return lines;
}
最佳答案
在每次迭代时,检查该行是否为空(或仅包含空格,具体取决于您真正想要的):
String line;
while ((line = reader.readLine()) != null) {
if (line.isEmpty()) { // or if (line.trim().isEmpty()) {
lines++;
}
}
请:
- 不要忽略异常。如果你不能处理它们,就把它们扔在这里
- 在finally block 中关闭阅读器
关于java-如何计算段落之间的空格并从总行数中减去它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9673481/