如何正确管理 OutputStream 以避免资源泄漏错误

How manage correctly a OutputStream to avoid resource leak errors

我被这个问题困扰了一段时间,我已经阅读了一些关于如何实现 inputStream 变量及其生命周期的教程和文档,但是我再次遇到了标记为 [=25= 的相同错误] 来自facebook的静态分析器,提示我在这段代码中有一个问题:RESOURCE_LEAK

File file = new File(PATH_PROFILE + UserHelper.getInstance().getUser().getId() + ".jpg");
    OutputStream os = null;
    try {
        os = new FileOutputStream(file);
        os.write(dataBytes);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (os != null) {
            try {
                os.flush();
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

描述错误为:

错误:RESOURCE_LEAK 在第 494 行通过调用 FileOutputStream(...) 获取的类型 java.io.FileOutputStream 的资源在第 499 行之后不会被释放。

但是我在finally块中释放了,这是误报?或者我错过了什么?因为我在这方面已经有一段时间了,我不知道错误在哪里。

非常感谢您的帮助和支持。

使用 try-with-resources(自 Java 7 起可用)。

File file = new File(PATH_PROFILE + UserHelper.getInstance().getUser().getId() + ".jpg");
try (OutputStream os = new FileOutputStream(file)) {
    os.write(dataBytes);
} catch (Exception e) {
    e.printStackTrace();
}

要了解更多信息,请阅读: