使用try-with-resources围绕扫描仪

Dil*_*ton 1 java netbeans file input

我创建了一个算法来读取文件并检查用户输入的多个问题.我正在使用Netbeans,它建议尝试使用资源.我不确定的是关闭文件.当我第一次创建算法时,我将file.close()放在错误的位置,因为无法访问它,因为它之前有一个"return"语句:

while (inputFile.hasNext()) {
        String word = inputFile.nextLine();
        for (int i = 0; i < sentance.length; i++) {
            for (int j = 0; j < punc.length; j++) {
                if (sentance[i].equalsIgnoreCase(word + punc[j])) {

                    return "I am a newborn. Not even a year old yet.";
                }
            }
        }
    }
    inputFile.close(); // Problem
Run Code Online (Sandbox Code Playgroud)

所以我用这个修好了:

        File file = new File("src/res/AgeQs.dat");
    Scanner inputFile = new Scanner(file);
    while (inputFile.hasNext()) {
        String word = inputFile.nextLine();
        for (int i = 0; i < sentance.length; i++) {
            for (int j = 0; j < punc.length; j++) {
                if (sentance[i].equalsIgnoreCase(word + punc[j])) {
                    inputFile.close(); // Problem fixed
                    return "I am a newborn. Not even a year old yet.";
                }
            }
        }  
    }
Run Code Online (Sandbox Code Playgroud)

问题是,当我以错误的方式设置时,Netbeans建议:

        File file = new File("src/res/AgeQs.dat");
    try (Scanner inputFile = new Scanner(file)) {
        while (inputFile.hasNext()) {
            String word = inputFile.nextLine();
            for (int i = 0; i < sentance.length; i++) {
                for (int j = 0; j < punc.length; j++) {
                    if (sentance[i].equalsIgnoreCase(word + punc[j])) {

                        return "I am a newborn. Not even a year old yet.";
                    }
                }
            }  
        }
    }
Run Code Online (Sandbox Code Playgroud)

是Netbeans纠正我的代码,还是只是删除文件的关闭?这是一个更好的方法吗?除非我确切地知道发生了什么,否则我不喜欢使用代码.

Evg*_*eev 5

try-with-resources可以保证AutoCloseable资源(如Scanner)始终处于关闭状态.关闭是由javac about隐式添加的.如

Scanner inputFile = new Scanner(file);
try {
    while (inputFile.hasNext()) {
        ....
    }
} finally {
    inputFile.close();
}
Run Code Online (Sandbox Code Playgroud)

顺便说一句,Netbeans没有注意到你的代码存在问题.扫描程序的方法不会抛出IOException但会抑制它.使用Scanner.ioException检查读取文件期间是否发生任何异常.