强化安全运行不合规代码
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 内,那么可能是什么问题?请帮助我。
最佳答案
您的工具可能担心的问题是,如果 GZIPInputStream
或 ObjectInputStream
在实例化期间抛出异常,则 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/