Java 使用try-and-catch计算文件中的行数

Java 使用try-and-catch计算文件中的行数,java,file,try-catch,java.util.scanner,Java,File,Try Catch,Java.util.scanner,我需要在使用“try”和“catch”时尝试计算文件中的行数。这就是我目前所拥有的。希望我能得到一些帮助。它只是一直在计时 public class LineCount { public static void main(String[] args) { try { Scanner in = new Scanner(new FileReader("data.txt")); int count = 0; //Stri

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



}

}

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

另外,如果使用
BufferedReader
as比标准扫描仪速度更快,效果会更好。虽然如果文件很小,但出于可读性目的,您可能不需要。但这取决于你。无论如何 给你:

//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()
方法将返回下一换行符之前的所有字符,并使用换行符本身

<> P>代码要考虑的另一件事是资源管理。打开
扫描仪
后,当不再读取时,应将其关闭。这可以通过程序末尾的
in.close()
来完成。实现这一点的另一种方法是设置try-with-resources块。要执行此操作,只需按如下方式移动
扫描仪
声明:

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

关于try-catch块的需要,作为Java编译过程的一部分,如果检查的异常是从方法捕获或抛出的,那么将检查这些异常。选中的异常是不是
运行时异常
s或
错误
s的所有异常。

为什么在此处尝试与thw计数相关的捕获?您从未调用下一行,因此
扫描仪
停留在第一行(意味着始终有“下一行”)。在
while
循环中添加对.nextLine()中
的调用。这将把扫描器的“指针”移到下一行。@code\u我收到一个错误,上面写着“LineCount.java:16:error:unreported exception FileNotFoundException;必须捕获或声明抛出scanner in=new scanner(new FileReader(“data.txt”);“如果我不使用try catch,我想,@Zephyr已经回答了代码中的问题,我所指的是问题陈述,它是不清楚的。这有一个简单的三行,涉及
LineNumberReader