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

问题描述 投票:1回答:3

我已经创建了一个算法来读取文件并检查用户输入的多个问题。我正在使用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

所以我用这个修好了:

        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.";
                }
            }
        }  
    }

问题是,当我以错误的方式设置时,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.";
                    }
                }
            }  
        }
    }

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

java file netbeans input
3个回答
5
投票

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

Scanner inputFile = new Scanner(file);
try {
    while (inputFile.hasNext()) {
        ....
    }
} finally {
    inputFile.close();
}

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


1
投票

阅读this,Java 7的try-with-resource块。

try-with-resources语句确保在语句结束时关闭每个资源。

Java 6不支持try-with-resources;您必须显式关闭IO流。


1
投票

是Netbeans纠正我的代码,还是只是删除文件的关闭?

它正在纠正你的代码。 try-with-resource具有隐式finally子句,用于关闭在资源部分中声明/创建的资源。 (所有资源必须实现Closeable接口...)

© www.soinside.com 2019 - 2024. All rights reserved.