FindBugs - "may not close the stream" when using ObjectOutputStream

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

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 continues to complain about the line:

 s = new ObjectOutputStream(out); 

that "may not close the stream" - BAD_PRACTICE - OS_OPEN_STREAM. Can anyone help?

+8
java stream findbugs software-quality
source share
2 answers

I think FindBugs does not detect that IOUtils.closeQuietly (out) is closing.

In any case, just close the ObjectOutputStream and it will close the underlying ByteArrayOutputStream. This is an implementation of ObjectOutputStream.close

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

to simplify the code

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

or if you are on Java 7

  ByteArrayOutputStream out = new ByteArrayOutputStream(); try (ObjectOutputStream s = new ObjectOutputStream(out)) { s.writeObject(1); } 
+8
source share

This means that s.close() will try to close the underlying thread, but this may not work. Therefore, to be sure that you must close it yourself. Try adding out.close() and see if the warning disappears.

+1
source share

All Articles