2

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

1 回答 1

1

“解决这个问题的方法是实现你自己的 SocketFactory 并用 SocketClient.setSocketFactory 设置它(FTPClient 是 SocketClient 的子类)。当你实现 SocketFactory 时,添加一个 setConnectTimeout 方法或类似的方法。在 createSocket 方法中,使用J2SE 1.4 连接方法超时。”

请参阅“如何设置连接超时?” Commons Net FAQ上的问题 ,为什么会这样。

于 2012-10-01T22:07:27.003 回答