加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 05:33:03 所属栏目:Java 来源:网络整理
导读:我想知道为什么我会得到这个新的 eclipse Juno的警告,尽管我认为我正确地关闭了一切.你能告诉我为什么我在下面的代码中得到这个警告? public static boolean copyFile(String fileSource,String fileDestination){ try { // Create channel on the source (
我想知道为什么我会得到这个新的 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版本好多了:)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读