问题描述
在我的Java代码中,我启动了一个新进程,然后获取其输入流以进行读取:
In my Java code, I start a new process, then obtain its input stream to read it:
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
FindBugs在此处报告错误:
FindBugs reports an error here:
may fail to close stream
Pattern id: OS_OPEN_STREAM, type: OS, category: BAD_PRACTICE
我必须关闭另一个进程的InputStream吗?而且,根据它的Javadoc ,InputStream#close()不执行任何操作.那么,这是一个误报吗?还是我应该在完成后真正关闭流程的输入流?
Must I close the InputStream of another process? And what's more, according to its Javadoc, InputStream#close() does nothing. So is this a false positive, or should I really close the input stream of the process when I'm done?
推荐答案
在这种情况下,您要close()
Reader
,这将关闭其基础流.是的,关闭流始终是一个好习惯,即使此刻您知道您要查看的实现并没有做任何事情(尽管实际上,它在这里完成了!).如果以后改变了怎么办?
In this case, you want to close()
the Reader
, which will close its underlying streams. Yes, it's always good practice to close streams, even if at the moment you know the implementation you're looking at doesn't do anything (though, in fact, it does here!). What if that changed later?
FindBugs仅用于警告可能的错误;它不一定总能确定.
FindBugs is only there to warn about possible errors; it can't always know for sure.
最后是的,您的Java进程拥有您生成的进程和Process
对象.您绝对需要关闭它和输出流.没有其他人在使用它们,并且,重要的是要做这些事情,以避免与OS相关的流搞笑业务.
Finally yes, your Java process owns the process and Process
object you spawned. You most definitely need to close that and the output stream. Nobody else is using them, and, it's important to do such things to avoid OS-related stream funny business.
这篇关于FindBugs:“可能无法关闭流" -在InputStream的情况下这有效吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!