如何正确关闭从FileOutputStream获取的FileChannel

kay*_*ahr 4 java eclipse nio eclipse-juno

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

FileChannel out = new FileOutputStream(file).getChannel();
try
{
    ...Do something with out...
}
finally
{
    out.close();
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

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

你怎么看?是否真的有必要关闭频道和流?或者正在关闭足够的流?

kay*_*ahr 9

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

If this stream has an associated channel then the channel is closed as well.
Run Code Online (Sandbox Code Playgroud)

所以关闭流就足够了.