2012-10-01 33 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 为什么这是如此。