我试图通过Scanner类读取java中的段落并打印出该行。但是,我遇到了一个非常奇怪的问题。我收到以下错误:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.base/java.util.Scanner.nextLine(Unknown Source)
at Test.main(Test.java:10)
之前的打印不是文件的结尾。打印在每次特定行的第一个单词处停止,文件中还有5-6行。
我的代码:
try {
Scanner scanner = new Scanner(new File(filename));
for (int i = 1; i < 3801; i++){
System.out.println(scanner.nextLine());
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
答案 0 :(得分:2)
使用以下内容确定文件结尾,而不是硬编码整数。
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
答案 1 :(得分:2)
您的scanner.nextLine()处于for循环中。
建议您改用while循环。
while循环的条件应该是scanner.hasNextLine()基本上转换为&#34;当扫描器在文件前面有另一行时,在while循环内运行代码,否则停止while-环路&#34;
这样,如果扫描仪没有更多行可供读取,它只会停止循环并继续其余的代码。
在你的for循环中,即使没有其他行可读,你也强迫扫描程序继续读取文件。
代码应为:
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(new File("read.txt"));
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
}
答案 2 :(得分:1)
显然java对文件的编码感到困惑,这就是它崩溃的原因。在扫描仪类中添加"UTF-8"
之后,它会读取所有内容。