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

前端之家收集整理的这篇文章主要介绍了java – Eclipse Juno:未分配的可关闭值前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想知道为什么我会得到这个新的 eclipse Juno的警告,尽管我认为我正确地关闭了一切.你能告诉我为什么我在下面的代码中得到这个警告?
  1. public static boolean copyFile(String fileSource,String fileDestination)
  2. {
  3. try
  4. {
  5. // Create channel on the source (the line below generates a warning unassigned closeable value)
  6. FileChannel srcChannel = new FileInputStream(fileSource).getChannel();
  7.  
  8. // Create channel on the destination (the line below generates a warning unassigned closeable value)
  9. FileChannel dstChannel = new FileOutputStream(fileDestination).getChannel();
  10.  
  11. // Copy file contents from source to destination
  12. dstChannel.transferFrom(srcChannel,srcChannel.size());
  13.  
  14. // Close the channels
  15. srcChannel.close();
  16. dstChannel.close();
  17.  
  18. return true;
  19. }
  20. catch (IOException e)
  21. {
  22. return false;
  23. }
  24. }

解决方法

如果您在Java 7上运行,则可以使用像这样的新的try-with-resources块,并且您的流将被自动关闭
  1. public static boolean copyFile(String fileSource,String fileDestination)
  2. {
  3. try(
  4. FileInputStream srcStream = new FileInputStream(fileSource);
  5. FileOutputStream dstStream = new FileOutputStream(fileDestination) )
  6. {
  7. dstStream.getChannel().transferFrom(srcStream.getChannel(),srcStream.getChannel().size());
  8. return true;
  9. }
  10. catch (IOException e)
  11. {
  12. return false;
  13. }
  14. }

您不需要明确地关闭底层渠道.但是,如果您不使用Java 7,则应该以繁琐的旧方式编写代码,最后是块:

  1. public static boolean copyFile(String fileSource,String fileDestination)
  2. {
  3. FileInputStream srcStream=null;
  4. FileOutputStream dstStream=null;
  5. try {
  6. srcStream = new FileInputStream(fileSource);
  7. dstStream = new FileOutputStream(fileDestination)
  8. dstStream.getChannel().transferFrom(srcStream.getChannel(),srcStream.getChannel().size());
  9. return true;
  10. }
  11. catch (IOException e)
  12. {
  13. return false;
  14. } finally {
  15. try { srcStream.close(); } catch (Exception e) {}
  16. try { dstStream.close(); } catch (Exception e) {}
  17. }
  18. }

看看Java 7版本好多了:)

猜你在找的Java相关文章