2012-08-07 38 views
9

我想知道为什么我会用新的日食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, 0, srcChannel.size()); 

     // Close the channels 
     srcChannel.close(); 
     dstChannel.close(); 

     return true; 
    } 
    catch (IOException e) 
    { 
     return false; 
    } 
} 

回答

16

如果你在Java 7的运行,你可以使用新的尝试,与资源块像这样,你的数据流会被自动关闭:

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

你不会需要明确关闭底层渠道。但是,如果你不使用的Java 7,你应该写在一个繁琐的老样子的代码,用finally块:

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

,请参阅Java 7的版本如何更好地为:)

+0

这个工程,但我想现在如何删除这个警告,而不使用此功能!为什么不能直接在资源中声明FileChannel。编辑:你只是回答我的问题,但为什么你不关闭fileChannel? – Abbadon 2012-08-07 07:45:50

+0

当你关闭流时,它会关闭通道。你不需要明确地关闭它。 – Strelok 2012-08-07 07:54:33

+0

我完全错过了(对于java7代码)新的FileInputStream和OutputStream的声明发生在打开try {}的括号之前。我想你提到过,通过调用它们来尝试与资源块。纠正后,警告消失。爱它! – 2017-11-20 12:03:00

4

你应该总是接近finally,因为如果有异常升高,你会不会关闭该资源。

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

注意:即使你把catch块中的回报,finally块就搞定。

+0

凭借该解决方案我得到未处理的IOexception! – Abbadon 2012-08-07 07:39:55

+0

那么这是一个例子,把一个catch(IOException ioe)块...... – 2012-08-07 07:49:50

3

eclipse正在警告你关于FileInputStreamFileOutputStream,你不能再引用。