gpt4 book ai didi

java - FindBugs OBL_UNSATISFIED_OBLIGATION

转载 作者:搜寻专家 更新时间:2023-10-31 08:03:46 26 4
gpt4 key购买 nike

我正在尝试使用 findBugs 查找遗留代码中的错误。在其中一种方法中,findBugs 给出了 OBL_UNSATISFIED_OBLIGATION 错误。我已验证所有流均已正确关闭。这是代码片段:

FileWriter fw = null;
FileReader fr = null;
try {
if (!new File(filePath).exists()) {
requiredStrings = CommandUtils.invoke(filename);
fw = new FileWriter(filePath);
fw.write(requiredStrings);
} else {
StringBuilder sb = new StringBuilder();
fr = new FileReader(filePath);

char[] buffer = new char[BLOCK_READ_SIZE];
int bytesRead;
while (-1 != (bytesRead = fr.read(buffer, 0, BLOCK_READ_SIZE))) {
sb.append(buffer, 0, bytesRead);
}
requiredStrings = sb.toString();
}
} finally {
if (fw != null) {
fw.close();
}
if (fr != null) {
fr.close();
}
}
return requiredStrings;

错误表明清理资源的义务未解除,Path continues at ....line....剩余义务{读者 x 1,作者 x-1}

最佳答案

您必须捕获 FileReader 和 FileWriter 在关闭时抛出的 IO 异常。您可以在 Java 7 及更高版本中执行此操作 try with resources

try (FileWriter fw = new FileWriter(filePath); FileReader fr = new FileReader(filePath)) {
/*your code here*/
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

还是用老方法

    FileWriter fw = null;
FileReader fr = null;
try {
/*your code here*/
fw = new FileWriter(filePath);
/*your code here*/
fr = new FileReader(filePath);
/*your code here*/
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fw != null) {
fw.close();
}
if (fr != null) {
fr.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

关于java - FindBugs OBL_UNSATISFIED_OBLIGATION,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18935881/

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