问题描述
在 C# 中,我几乎总是在处理流对象时使用 using
模式.例如:
In C#, I almost always use the using
pattern when working with stream objects. For example:
using (Stream stream = new MemoryStream())
{
// do stuff
}
通过使用 using
块,我们确保在代码块执行后立即在流上调用 dispose.
By using the using
block, we ensure that dispose is called on the stream immediately after that code bock executes.
我知道 Java 没有与 using
关键字等效的关键字,但我的问题是,在 Java 中使用像 FileOutputStream
这样的对象时,我们是否需要做任何家务以确保它得到处理?我正在查看 this 代码示例,我注意到他们什么都不做.
I know Java doesn't have the equivalent of a using
keyword, but my question is that when working with an object like a FileOutputStream
in Java, do we need to do any housekeeping to make sure it gets disposed? I was looking at this code example, and I noticed they don't do any.
我只是想知道 Java 在处理处理流方面的最佳实践是什么,或者它是否足以让垃圾收集器处理它.
I just wondered what the best practice was for Java in handling disposing streams, or if it's good enough to let the garbage collector handle it.
推荐答案
一般来说,你必须做到以下几点:
generally, you have to do the following:
InputStream stream = null;
try {
// IO stuff - create the stream and manipulate it
} catch (IOException ex){
// handle exception
} finally {
try {
stream.close();
} catch (IOException ex){}
}
但是 apache commons-io 提供了 IOUtils.closeQuietly(stream);
放在 finally
子句中以使其不那么难看.我认为在 Java 7 中会有一些改进.
But apache commons-io provides IOUtils.closeQuietly(stream);
which is put in the finally
clause to make it a little less-ugly. I think there will be some improvement on that in Java 7.
更新:Jon Skeet 发表了一个非常有用的评论,异常的实际处理很少发生在类本身中(除非它只是简单地记录它,但实际上并没有处理它).因此,您最好声明您的方法抛出该异常,或者将其包装在自定义异常中(简单的原子操作除外).
Update: Jon Skeet made a very useful comment, that the actual handling of the exception is rarely possible to happen in the class itself (unless it is simply to log it, but that's not actually handling it). So you'd better declare your method throw that exception up, or wrap it in a custom exception (except for simple, atomic operations).
这篇关于在 Java 中处理流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!