java - eclipse 朱诺 : unassigned closeable value

标签 java eclipse

我想知道为什么我会在新的 eclipse Juno 上收到这个警告,尽管我认为我正确地关闭了所有内容。您能告诉我为什么我会在以下代码中收到此警告吗?

public static boolean copyFile(String fileSource, String fileDestination)
{
    try
    {
        // Create channel on the source (the line below generates a warning unassigned closeable value) 
        FileChannel srcChannel = new FileInputStream(fileSource).getChannel(); 

        // Create channel on the destination (the line below generates a warning unassigned closeable value)
        FileChannel dstChannel = new FileOutputStream(fileDestination).getChannel();

        // Copy file contents from source to destination
        dstChannel.transferFrom(srcChannel, 0, srcChannel.size());

        // Close the channels
        srcChannel.close();
        dstChannel.close();

        return true;
    }
    catch (IOException e)
    {
        return false;
    } 
 }

最佳答案

如果您在 Java 7 上运行,您可以像这样使用新的 try-with-resources block ,您的流将自动关闭:

public static boolean copyFile(String fileSource, String fileDestination)
{
    try(
      FileInputStream srcStream = new FileInputStream(fileSource); 
      FileOutputStream dstStream = new FileOutputStream(fileDestination) )
    {
        dstStream.getChannel().transferFrom(srcStream.getChannel(), 0, srcStream.getChannel().size());
        return true;
    }
    catch (IOException e)
    {
        return false;
    } 
}

您不需要显式关闭底层 channel 。但是,如果您不使用 Java 7,则应使用 finally block 以繁琐的旧方式编写代码:

public static boolean copyFile(String fileSource, String fileDestination)
{
    FileInputStream srcStream=null;
    FileOutputStream dstStream=null;
    try {
      srcStream = new FileInputStream(fileSource); 
      dstStream = new FileOutputStream(fileDestination)
      dstStream.getChannel().transferFrom(srcStream.getChannel(), 0, srcStream.getChannel().size());
        return true;
    }
    catch (IOException e)
    {
        return false;
    } finally {
      try { srcStream.close(); } catch (Exception e) {}
      try { dstStream.close(); } catch (Exception e) {}
    }
}

看看 Java 7 版本有多好:)

关于java - eclipse 朱诺 : unassigned closeable value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11841033/

相关文章:

java - 更改 Spring 中 @Transactional 的默认设置

java - RadioButton 无效双

java - 如何在 RCP 工作台工具栏和 RCP View 之间进行通信

eclipse - hybris 5 Accelerator构建在Eclipse上失败,但在cmd上失败

java - 如何使用 HashMap 作为构建器?

java - 即使使用 ErrorHandler,为什么模式验证会在第一个错误后结束?

java - 我无法从另一个类获取 arrayList

java - 如何设置 USB 上的 Eclipse 以在没有管理员权限的计算机上使用?

java - Maven Eclipse 插件缺少 .jar 文件

c++ - 以万亿为单位的数字相乘时出错