9

我想知道为什么我会在新的 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;
    } 
 }
4

3 回答 3

16

如果您在 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,则应该以繁琐的旧方式编写代码,并带有 finally 块:

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

于 2012-08-07T07:25:17.960 回答
4

您应该始终关闭,finally因为如果出现异常,您将不会关闭资源。

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

注意:即使你在块中放了一个 return catchfinally块也会被完成。

于 2012-08-07T07:19:32.410 回答
3

eclipse 警告你关于FileInputStream并且FileOutputStream你不能再参考。

于 2012-08-07T07:21:23.333 回答