java – Eclipse Juno:未分配的可关闭值

前端之家收集整理的这篇文章主要介绍了java – Eclipse Juno:未分配的可关闭值前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想知道为什么我会得到这个新的 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,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(),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(),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版本好多了:)

原文链接:https://www.f2er.com/java/122194.html

猜你在找的Java相关文章