逐行读取 java 中的文件在最后一行之后出现异常



我遇到了一个问题,在我阅读最后一行后,我得到了一个没有这样的元素异常,我想知道如何修改 while 循环以避免这种情况?

File file = new File(fileName); 
Scanner fileInput;
String line;
try {
fileInput = new Scanner(file);
while ( (line = fileInput.nextLine() ) != null  ) {
System.out.println(line);
}
fileInput.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

这不是你应该使用扫描仪的方式,而且你混淆了如何使用BufferedReader和使用扫描仪的方式。 while 应该改为检查Scanner#hasNextLine()

while (fileInput.hasNextLine()) {
line = fileInput.nextLine();
// use line here
}

或者,您可以使用试用资源,例如:

File file = new File(fileName); 
String line = "";
// use try-with resources
try (Scanner fileInput = new Scanner(file) {
while (fileInput.hasNextLine() ) {
line = fileInput.nextLine();
System.out.println(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// no need to close Scanner/File as the try-with-resources does this for you