FindBugs - “可能无法关闭流”使用ObjectOutputStream时 [英] FindBugs - "may fail to close stream" when using ObjectOutputStream
问题描述
我有这段代码,即将Ojbect写入字节数组流:
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();
}
然而,FindBugs一直在抱怨行:
However, FindBugs keeps complaining about line:
s = new ObjectOutputStream(out);
可能无法关闭流 - BAD_PRACTICE - OS_OPEN_STREAM。有人可以帮忙吗?
that "may fail to close stream" - BAD_PRACTICE - OS_OPEN_STREAM. Can somebody help?
推荐答案
我认为FindBugs并不认为IOUtils.closeQuietly(out)会关闭。
I think FindBugs does not undestand that IOUtils.closeQuietly(out) closes out.
无论如何,关闭ObjectOutputStream就足够了,它将关闭底层的ByteArrayOutputStream。这是ObjectOutputStream.close实现
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();
}
因此您可以简化代码
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream s = new ObjectOutputStream(out);
try {
s.writeObject(1);
} finally {
IOUtils.closeQuietly(s);
}
或者如果您使用的是Java 7
or if you are in Java 7
ByteArrayOutputStream out = new ByteArrayOutputStream();
try (ObjectOutputStream s = new ObjectOutputStream(out)) {
s.writeObject(1);
}
这篇关于FindBugs - “可能无法关闭流”使用ObjectOutputStream时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!