2012-08-07 65 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,你不能再引用。