4

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

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 块,这一切都会变得臃肿。

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

4

1 回答 1

9

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

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

所以关闭流就足够了。

于 2012-06-15T11:27:58.290 回答