提问人:Adaxil 提问时间:10/13/2022 更新时间:10/13/2022 访问量:21
为什么此代码停止使用 Scanner 读取文件上的行?(爪哇)
Why does this code stop reading the lines on my file with Scanner? (java)
问:
我有这个停止扫描我的.txt文件的 java 代码,奇怪的是这只发生在我的 PC 上,我有同学使用他们的笔记本电脑或实验室 PC,即使代码完全相同,它们也能正常工作,图像上的更多细节:
package lab07;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Rankings {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(System.in);
Scanner archivo = new Scanner(new File("C:\\Users\\adxlm\\Downloads\\IMDB.txt"));
System.out.print("Enter the quantity of rankings: ");
// int nrorankings = input.nextInt();
for (int i = 0; i < 100; i++) {
System.out.println(archivo.nextLine());
}
}
}
它在第 24 行停止打印,如图所示:
20 8.6 612312 City of God (2002)
21 8.6 1065032 Star Wars: Episode IV - A New Hope (1977)
22 8.6 1206250 Se7en (1995)
23 8.6 403913 Avengers: Infinity War (2018)
24 8
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.base/java.util.Scanner.nextLine(Scanner.java:1651)
at lab07.peliculas.main(peliculas.java:12)
这是当时.txt文件 https://i.stack.imgur.com/1hCjp.jpg
先谢谢你们!
答:
0赞
Guillermo Guerrero
10/13/2022
#1
您应该使用 BufferReader 而不是 Scanner:
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(System.in);
BufferedReader archivo = new BufferedReader(new FileReader("C:\\Users\\adxlm\\Downloads\\IMDB.txt"));
System.out.print("Enter the quantity of rankings: ");
try {
String line = archivo.readLine();
while (line != null) {
System.out.println(line);
line = archivo.readLine();
}
archivo.close();
} catch (
IOException e) {
e.printStackTrace();
}
}
评论