7

我正在尝试使用 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;

该错误表明清理资源的义务未解除,路径继续在....行.... 剩余义务 {Reader x 1, Writer x-1}

4

2 回答 2

0

您必须在 FileReader 和 FileWriter 关闭时捕获它们抛出的 IO 异常。您可以在 Java 7 及更高版本中 尝试使用资源

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();
        }
    }
}
于 2017-10-29T19:56:02.577 回答
0

在一个方法中,它打开一个InputStream用于读取,如果该方法有可能在没有关闭此InputStream对象的情况下退出,FindBugs 会抱怨无法清理 java.io.InputStream 检查异常。例如:

void readProperties() throws FooException{
    InputStream is= ...
    PropertyFactory.getInstance().loadXXXFromPropertyStream(is); // it throws FooException
    is.close(); // maybe never called for a FooException leaving inputstream is open.
}
于 2018-03-09T13:02:47.693 回答