我使用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.");
}
}