繁体   English   中英

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

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

我需要在使用“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();}



}

}

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

此外,如果您使用BufferedReader比标准扫描仪更快,那会更好。 尽管文件很小,但出于可读性目的,您可能不会这样做。 但这取决于你。 反正。 这里是 go:

//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;
}

可能你的问题g 已经被回答了,你不应该在搜索之前问已经回答的问题,至少有一段时间。

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

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

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

关于 try-catch 块的需要,作为 Java 编译过程的一部分,将检查检查异常是否从方法中捕获或抛出。 Checked-exceptions 是所有不是RuntimeException s 或Error s 的东西。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM