强化安全运行不合规代码
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();
}
}
我在 Kotlin 代码中遇到了同样的错误,正如 Slaw 建议的上述解决方案是使用 try 与 Kotlin 中类似的资源,即
use
。参考https://www.baeldung.com/kotlin/try-with-resources