我使用org.apache.commons.net.ftp.FtpClient创建了一个可靠的FTP类,可以并行下载多个文件,并在失败时重试。
奇怪的是,我似乎无法让代码识别失败。例如,如果我在传输过程中拉出以太网电缆,代码似乎就会继续阻塞:
client.retrieveFile(nextFile, ftpOutputStream);
线。有人可以告诉我它为什么阻止这一行而不是返回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.");
}
}
答案 0 :(得分:1)
“解决这个问题的方法是实现自己的SocketFactory并使用SocketClient.setSocketFactory设置它(FTPClient是SocketClient的子类)。当你实现SocketFactory时,添加一个setConnectTimeout方法或类似的东西。在createSocket方法里面,使用J2SE 1.4 connect方法和超时。“
请参阅“如何设置连接超时?”关于Commons Net FAQ的问题 为什么会这样。