[英]Should I close the InputStream of org.apache.commons.io.IOUtils
I'm using the answer on How to convert InputStream to virtual File which uses org.apache.commons.io.IOUtils
to copy the given InputStream
to a FileOutputStream
in order to create a File
. 我正在使用如何将InputStream转换为虚拟文件的答案,该文件使用
org.apache.commons.io.IOUtils
将给定的InputStream
复制到FileOutputStream
以创建File
。
Should I close the InputStream
given? 我应该关闭给出的
InputStream
吗?
It is a best practice to close InputStream. 关闭InputStream是最佳做法。 See this question .
看到这个问题 。
org.apache.commons.io.IOUtils.copy
do not close streams. org.apache.commons.io.IOUtils.copy
不关闭流。 So you have to close. 所以你必须关闭。
Wherever possible, the methods in this class do not flush or close the stream.
只要有可能,此类中的方法不会刷新或关闭流。 This is to avoid making non-portable assumptions about the streams' origin and further use.
这是为了避免对流的来源和进一步使用做出不可移植的假设。 Thus the caller is still responsible for closing streams after use.
因此,呼叫者仍然负责在使用后关闭流。
Edit : After reading the question again I have to correct my answer because the question apparently was about the InputStream
from the referenced answer and not the OutputStream
. 编辑 :再次阅读问题后,我必须更正我的答案,因为问题显然是来自引用答案的
InputStream
而不是OutputStream
。 The InputStream
needs to be closed (see the answer from @Adi). 需要关闭
InputStream
(请参阅@Adi的答案)。 The OutputStream
however is in the try-with-resources Statement so that's the one you don't need to close. 然而,
OutputStream
位于try-with-resources语句中,因此您不需要关闭它。
The answer that is referenced in the question is using the Java 7 try-with-resources Statement which ensures that the resource is closed at the end of the statement. 问题中引用的答案是使用Java 7 try-with-resources语句 ,该语句确保在语句结束时关闭资源。
The try-with-resources statement is a try statement that declares one or more resources.
try-with-resources语句是一个声明一个或多个资源的try语句。 A resource is an object that must be closed after the program is finished with it.
资源是在程序完成后必须关闭的对象。 The try-with-resources statement ensures that each resource is closed at the end of the statement.
try-with-resources语句确保在语句结束时关闭每个资源。
So for the OutputStream
, NO , in that particular case you don't need to close the OutputStream
yourself, provided you are using try-with-resource. 因此对于
OutputStream
, NO ,在这种特殊情况下,如果您使用的是try-with-resource,则不需要自己关闭OutputStream
。
The InputStream
however needs to be closed . 但是, 需要关闭
InputStream
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.