使用 try 和 catch 计算文件中的行数

Counting the number of lines in a file using try and catch

提问人:snk 提问时间:3/23/2021 更新时间:3/23/2021 访问量:131

问:

我需要尝试在使用“try”和“catch”时计算文件中的行数。这就是我目前所拥有的。希望我能得到一些帮助。它只是不断超时。

public class LineCount {

public static void main(String[] args) {

    try {
        Scanner in = new Scanner(new FileReader("data.txt"));

        int count = 0;
        //String line;
        //line = in.readLine();
        while (in.hasNextLine()) {
            count++;

        }
        System.out.println("Number of lines: " + count);

    }catch (Exception e){e.printStackTrace();}



}

}

爪哇岛 文件 try-catch(尝试捕捉) java.util.scanner

评论

1赞 code_mechanic 3/23/2021
为什么在这里尝试与计数相关的 try-catch?

答:

0赞 Kostas Thanasis 3/23/2021 #1

它超时,因为您没有推进 .如果你进入while循环,你将永远不会退出它。Scanner

此外,如果您按原样使用比标准扫描仪更快,那就更好了。尽管如果文件很小,也许出于可读性目的,您不会这样做。但这取决于你。无论如何。 给你:BufferedReader

//this is the try-with-resources syntax
//closing the autoclosable resources when try catch is over
try (BufferedReader reader = new BufferedReader(new FileReader("FileName"))){
    
    int count = 0;
    while( reader.readLine() != null){
        count++;
    }
    System.out.println("The file has " + count + " lines"); 
}catch(IOException e){
    System.out.println("File was not found");
    //or you can print -1;
}

可能你的问题已经得到回答,至少在一段时间内,你不应该在搜索之前问已经回答过的问题。

0赞 Geoffrey Casper 3/23/2021 #2

似乎您正在做所有事情,但使用换行符。要执行此操作,只需在循环中运行即可。此方法将返回下一个换行符之前的所有字符,并使用换行符本身。java.util.Scannerin.nextLine()whileScanner.nextLine()

代码要考虑的另一件事是资源管理。打开 后,当它不再被读取时,它应该被关闭。这可以在程序结束时完成。实现此目的的另一种方法是设置一个 try-with-resources 块。为此,只需像这样移动您的声明:Scannerin.close()Scanner

try (Scanner in = new Scanner(new FileReader("data.txt"))) {

关于对 try-catch 块的需求,作为 Java 编译过程的一部分,如果检查异常被捕获或从方法中抛出,将对其进行检查。选中的异常是不是 s 或 s 的所有内容。RuntimeExceptionError