繁体   English   中英

Eclipse Juno:未分配的可关闭值

[英]Eclipse Juno : unassigned closeable value

我想知道为什么我会用新的日食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块,你的流将自动关闭:

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;
    } 
}

您不需要显式关闭底层渠道。 但是,如果你不使用Java 7,你应该用一种繁琐的旧方式编写代码,最后使用块:

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版本有多好:)

你应该总是关闭finally ,因为如果有异常升高,你会不会关闭该资源。

FileChannel srcChannel = null
try {
   srcChannel = xxx;
} finally {
  if (srcChannel != null) {
    srcChannel.close();
  }
}

注意:即使你在catch块中放了一个return,也会完成finally块。

eclipse警告你不能再引用的FileInputStreamFileOutputStream

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM