【问题标题】:How to properly close a FileChannel obtained from a FileOutputStream如何正确关闭从 FileOutputStream 获得的 FileChannel
【发布时间】:2012-06-18 11:17:10
【问题描述】:

我刚刚在当前的 Ecipe Juno 候选版本中打开了一些旧代码,并注意到一个闪亮的新警告:资源泄漏。它是由这样的代码触发的:

FileChannel out = new FileOutputStream(file).getChannel();
try
{
    ...Do something with out...
}
finally
{
    out.close();
}

Eclipse 认为创建的文件输出流是资源泄漏。实际上,我不确定这是否是错误警告(并且 FileChannel 的 close 方法也不会关闭流),或者这是否真的是资源泄漏。我将代码更改为:

FileOutputStream outStream = new FileOutputStream(file);
try
{
    FileChannel out = outStream.getChannel();
    ...Do something with out...
}
finally
{
    outStream.close();
}

警告现在消失了,但现在我不确定是否必须调用 FileChannel 的 close 方法。所以也许它必须看起来像这样:

FileOutputStream outStream = new FileOutputStream(file);
try
{
    FileChannel out = outStream.getChannel();
    try
    {
        ...Do something with out...
    }
    finally
    {
        out.close();
    }
}
finally
{
    outStream.close();
}

如果使用文件输入通道和文件输出通道,那么这会导致四个嵌套的 try...finally 块,这一切都会变得臃肿。

你怎么看?真的有必要关闭频道和流吗?还是关闭流就够了?

【问题讨论】:

    标签: java eclipse nio eclipse-juno


    【解决方案1】:

    啊,在FileOutputStream的close()方法的文档中找到了答案:

    If this stream has an associated channel then the channel is closed as well.
    

    所以关闭流就足够了。

    【讨论】:

      猜你喜欢
      • 2012-05-27
      • 1970-01-01
      • 1970-01-01
      • 2013-05-05
      • 1970-01-01
      • 2010-12-08
      • 2022-01-23
      • 2021-12-25
      • 2014-03-05
      相关资源
      最近更新 更多