逐行读取Java文件,最后一行后出现异常

时间:2018-09-30 20:53:03

标签: java file

我遇到一个问题,当我读完最后一行后,没有得到这样的元素异常,我想知道如何修改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();
}

1 个答案:

答案 0 :(得分:2)

这不是您应该使用扫描仪的方式,并且使您如何将BufferedReader与如何使用扫描仪相混淆。而while应该检查Scanner#hasNextLine()

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

或者您可以使用try-with-resources,例如:

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