在使用"尝试";以及";捕获";。这就是我到目前为止所拥有的。希望我能得到一些帮助。它只是一直在拖延时间。
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();}
}
}
除了使用换行符之外,似乎什么都在做。要使用java.util.Scanner
执行此操作,只需在while
循环中运行in.nextLine()
即可。此Scanner.nextLine()
方法将返回下一个换行符之前的所有字符,并消耗换行符本身。
代码中需要考虑的另一件事是资源管理。打开Scanner
后,当它不再被读取时,它应该被关闭。这可以在程序结束时使用in.close()
来完成。实现这一点的另一种方法是设置一个带有资源的try块。要做到这一点,只需像这样移动Scanner
声明:
try (Scanner in = new Scanner(new FileReader("data.txt"))) {
关于try-catch块的需要,作为Java编译过程的一部分,如果已检查异常是从方法捕获或抛出的,则会对其进行检查。检查的异常是不是RuntimeException
s或Error
s的所有异常。
它超时是因为您没有推进Scanner
。如果你进入while循环,你将永远不会退出它。
此外,如果您使用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;
}
也许你的问题已经被回答了,你不应该在搜索之前问已经回答的问题,至少在一段时间内。