FindBugs - "may fail to close stream" when using ObjectOutputStream

Eugene picture Eugene · Jan 21, 2013 · Viewed 10.5k times · Source

I have this piece of code, which is to write an Ojbect to a byte array stream:

     static byte[] toBytes(MyTokens tokens) throws IOException {
        ByteArrayOutputStream out = null;
        ObjectOutput s = null;
        try {
            out = new ByteArrayOutputStream();
            try {
                s = new ObjectOutputStream(out);
                s.writeObject(tokens);
            } finally {
                try {
                    s.close();
                } catch (Exception e) {
                    throw new CSBRuntimeException(e);
                }             
            }
        } catch (Exception e) {
            throw new CSBRuntimeException(e);
        } finally {
            IOUtils.closeQuietly(out);
        }
        return out.toByteArray();
    }

However, FindBugs keeps complaining about line:

s = new ObjectOutputStream(out);

that "may fail to close stream" - BAD_PRACTICE - OS_OPEN_STREAM. Can somebody help?

Answer

Evgeniy Dorofeev picture Evgeniy Dorofeev · Jan 21, 2013

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