FindBugs - “may fail to close stream” when using ObjectOutputStream

こ雲淡風輕ζ 提交于 2019-12-04 03:12:14

I think FindBugs does not undestand that IOUtils.closeQuietly(out) closes out.

Anyway it is enough to close ObjectOutputStream and it will close underlying ByteArrayOutputStream. This is ObjectOutputStream.close implementation

public void close() throws IOException {
    flush();
    clear();
    bout.close();
}

so you can simplify your code

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ObjectOutputStream s = new ObjectOutputStream(out);
    try {
        s.writeObject(1);
    } finally {
        IOUtils.closeQuietly(s);
    }

or if you are in Java 7

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try (ObjectOutputStream s = new ObjectOutputStream(out)) {
        s.writeObject(1);
    }

It means that s.close() will try to close underlying stream, but it may fail to do it. So to be sure you should close it on your own also. Try to add out.close() and see if warning disappears.

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