在Java中使用FTP并检测断开连接
我曾经创建过一个可靠的FTP类,它应该并行下载多个文件,并在失败时重试 奇怪的是,我似乎无法让代码识别故障。例如,如果我在传输过程中拉动以太网电缆,代码似乎在“”上继续阻塞。在Java中使用FTP并检测断开连接,java,exception,networking,ftp,Java,Exception,Networking,Ftp,我曾经创建过一个可靠的FTP类,它应该并行下载多个文件,并在失败时重试 奇怪的是,我似乎无法让代码识别故障。例如,如果我在传输过程中拉动以太网电缆,代码似乎在“”上继续阻塞。 client.retrieveFile(nextFile, ftpOutputStream); 线路。有人能告诉我为什么它会阻塞这一行,而不是返回false或抛出异常吗?我是否错过了设置超时或类似的设置 try { OutputStream ftpOutputStream = new FileOutputStre
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.");
}
}
解决此问题的方法是实现您自己的SocketFactory并使用SocketClient.setSocketFactory(FTPClient是SocketClient的子类)进行设置。实现SocketFactory时,请添加setConnectTimeout方法或类似方法。在createSocket方法内,使用J2SE 1.4 connect方法和超时
请参阅上的“如何设置连接超时?”问题
为什么会这样