Fortify security issue “Unreleased resource stream” for try-with-resource

走远了吗. 提交于 2021-02-11 14:34:11

问题


Fortify security run Noncompliant Code

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

It is saying "Unreleased Resource: Streams" , but it is inside try-with-resource then what can be the issue? please help me.


回答1:


Likely the issue your tool is worried about is if GZIPInputStream or ObjectInputStream throws an exception during instantiation, then the FileInputStream won't be closed. You can try the following:

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();
    }
}


来源:https://stackoverflow.com/questions/56289611/fortify-security-issue-unreleased-resource-stream-for-try-with-resource

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!