Java – eclipse Juno: unassigned closable value

I wonder why I got the warning of this new eclipse Juno, although I think I closed everything correctly Can you tell me why I get this warning in the following code?

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

Solution

If you run on Java 7, you can use a new try with resources block like this, and your flow will be closed automatically:

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

You do not need to explicitly close the underlying channels However, if you don't use Java 7, you should write code in a cumbersome old way, ending with blocks:

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) {}
    }
}

Look at the Java 7 version:)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>