尝试使用资源强化安全问题“未发布的资源流”

时间:2019-05-24 09:25:01

标签: java file-io fortify objectinputstream

加强安全性运行不合规代码

public static A read(String path) throws IOException, ClassNotFoundException {
    try (ObjectInputStream os = new ObjectInputStream(new GZIPInputStream(new FileInputStream(path)))) {
        return (A) os.readObject();
    }
}

它说的是“未发布的资源:流”,但是它在try-with-resource内部,那么可能是什么问题?请帮助我。

1 个答案:

答案 0 :(得分:0)

您的工具可能担心的问题是,如果GZIPInputStreamObjectInputStream在实例化期间引发异常,则FileInputStream将不会关闭。您可以尝试以下操作:

public static A read(String path) throws IOException, ClassNotFoundException {
    try (FileInputStream fileInput = new FileInputStream(path);
         GZIPInputStream gzipInput = new GZIPInputStream(fileInput);
         ObjectInputStream objectInput = new ObjectInputStream(gzipInput)) {
        return (A) objectInput.readObject();
    }
}