gpt4 book ai didi

java - 使用 try-with-resources 包围扫描仪

转载 作者:行者123 更新时间:2023-11-29 06:39:39 26 4
gpt4 key购买 nike

我创建了一种算法来读取文件并检查用户输入的多个问题。我正在使用 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 是在更正我的代码,还是只是删除了文件的关闭?这是执行此操作的更好方法吗?我不喜欢使用代码,除非我确切地知道发生了什么。

最佳答案

try-with-resources 保证 AutoCloseable 资源(如 Scanner)将始终关闭。关闭是由 javac 大约隐式添加的。作为

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

顺便说一句,您的代码中存在 Netbeans 未能注意到的问题。 Scanner 的方法不会抛出 IOException 但会抑制它。使用 Scanner.ioException 检查读取文件时是否发生异常。

关于java - 使用 try-with-resources 包围扫描仪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14078451/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com