gpt4 book ai didi

java - 强化 try-with-resource 的安全问题 "Unreleased resource stream"

转载 作者:行者123 更新时间:2023-12-02 05:16:33 24 4
gpt4 key购买 nike

强化安全运行不合规代码

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

它说的是“未释放的资源:Streams”,但它位于 try-with-resource 内,那么可能是什么问题?请帮助我。

最佳答案

您的工具可能担心的问题是,如果 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();
}
}

关于java - 强化 try-with-resource 的安全问题 "Unreleased resource stream",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56289611/

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