在Java中部署流 [英] disposing streams in Java

查看:92
本文介绍了在Java中部署流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,在使用流对象时,我几乎总是使用使用模式。例如:

In C#, I almost always use the using pattern when working with stream objects. For example:

        using (Stream stream = new MemoryStream())
        {
            // do stuff
        }

使用使用 block,我们确保在代码块执行后立即在流上调用dispose。

By using the using block, we ensure that dispose is called on the stream immediately after that code bock executes.

我知道Java没有相当于使用关键字,但我的问题是,当使用Java中的 FileOutputStream 这样的对象时,我们是否需要进行任何内务管理以确保它被处置?我正在查看这个代码示例,我注意到了他们没有做任何事情。

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中部署流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆