9

すべてを正しく閉じたと思うのに、なぜ新しい日食ジュノでこの警告が表示されるのか疑問に思っています。次のコードでこの警告が表示される理由を教えてください。

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

IF you're running on Java 7, you can use the new try-with-resources blocks like so, and your streams will be automatically closed:

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

You won't need to explicitly close the underlying channels. However if you're not using Java 7, you should write the code in a cumbersome old way, with finally 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(), 0, srcStream.getChannel().size());
        return true;
    }
    catch (IOException e)
    {
        return false;
    } finally {
      try { srcStream.close(); } catch (Exception e) {}
      try { dstStream.close(); } catch (Exception e) {}
    }
}

See how much better the Java 7 version is :)

于 2012-08-07T07:25:17.960 に答える
4

finally例外が発生した場合、リソースをクローズしないため、常にクローズする必要があります。

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

catch注意:ブロックにリターンを入れてもブロックfinallyは成立します。

于 2012-08-07T07:19:32.410 に答える
3

FileInputStreameclipse は、およびFileOutputStreamを参照できなくなったことを警告しています。

于 2012-08-07T07:21:23.333 に答える