我应该关闭 org.apache.commons.io.IOUtils 的 InputStream 吗?
Should I close the InputStream of org.apache.commons.io.IOUtils
我正在使用 How to convert InputStream to virtual File 上的答案,它使用 org.apache.commons.io.IOUtils
将给定的 InputStream
复制到 FileOutputStream
以创建 File
.
我应该关闭给定的 InputStream
吗?
最好关闭 InputStream。看到这个 question.
org.apache.commons.io.IOUtils.copy
不关闭流。所以你必须关闭。
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.
编辑:再次阅读问题后,我必须更正我的答案,因为问题显然是关于参考答案中的 InputStream
而不是 OutputStream
. InputStream
需要关闭(请参阅@Adi 的回答)。然而,OutputStream
位于 try-with-resources 语句中,因此您不需要关闭它。
问题中引用的答案是使用 Java 7 try-with-resources Statement 确保资源在语句末尾关闭。
The try-with-resources statement is a try statement that declares one
or more resources. 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.
所以对于 OutputStream
,NO,在那种特殊情况下你不需要自己关闭 OutputStream
,只要你使用 try -有资源。
InputStream
但是需要关闭。
我正在使用 How to convert InputStream to virtual File 上的答案,它使用 org.apache.commons.io.IOUtils
将给定的 InputStream
复制到 FileOutputStream
以创建 File
.
我应该关闭给定的 InputStream
吗?
最好关闭 InputStream。看到这个 question.
org.apache.commons.io.IOUtils.copy
不关闭流。所以你必须关闭。
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.
编辑:再次阅读问题后,我必须更正我的答案,因为问题显然是关于参考答案中的 InputStream
而不是 OutputStream
. InputStream
需要关闭(请参阅@Adi 的回答)。然而,OutputStream
位于 try-with-resources 语句中,因此您不需要关闭它。
问题中引用的答案是使用 Java 7 try-with-resources Statement 确保资源在语句末尾关闭。
The try-with-resources statement is a try statement that declares one or more resources. 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.
所以对于 OutputStream
,NO,在那种特殊情况下你不需要自己关闭 OutputStream
,只要你使用 try -有资源。
InputStream
但是需要关闭。