2012-10-01 32 views
2

我已使用org.apache.commons.net.ftp.FtpClient創建可以並行下載多個文件並在失敗時重試的可靠FTP類。在Java中使用FTP並檢測斷開連接

奇怪的是,我似乎無法讓代碼識別失敗。例如,如果我在傳輸過程中拉動以太網電纜,則代碼似乎繼續阻止:

client.retrieveFile(nextFile, ftpOutputStream); 

line。有人能告訴我爲什麼它會阻止這行,而不是返回false或拋出異常?我錯過了設置超時或類似的東西嗎?

try { 
    OutputStream ftpOutputStream = new FileOutputStream(fileName); 

    System.out.println("Attempting to retrieve file [" + nextFile + "]."); 
    success = iclient.retrieveFile(nextFile, ftpOutputStream); 
    System.out.println("Returned from retrieving file [" + nextFile + "]."); 

    ftpOutputStream.close(); 
} 

//Can fail due to FTPConnectionClosedException, CopyStreamException, or IOException. In any case, best course 
//of action is to simply create a new connection, log in again, and change back to target directory. 
catch(Exception ex) { 

    try { 
     System.out.println("Error occurred during download, deleting file and restarting."); 
     Thread.sleep(1000); 

     //Delete the failed file assuming any of it got written to the local drive. 
     File f = new File(fileName);       
     if(f.exists()) { 
      System.out.println("Deleting file..."); 
      f.delete(); 
     }    

     Thread.sleep(5000); 
    } 
    catch (InterruptedException iex) { 
     System.out.println("Interrupted exceptoin while respoding to failed FTP attempt."); 
    } 
} 

回答

1

「要解決這個問題的方法是實現自己的SocketFactory與SocketClient.setSocketFactory設置(FTPClient是SocketClient的子類)。當你實現的SocketFactory,加setConnectTimeout方法或一些這樣的。裏面的createSocket方法,請使用帶有超時的J2SE 1.4連接方法。「

請參閱「如何設置連接超時?」問題在Commons Net FAQ 爲什麼這是如此。