Java FTP Transfer断开检测

时间:2014-09-15 09:39:53

标签: java ftp apache-commons

我正在编写一段简单的java代码,用于将文件从HTTP站点传输到本地计算机。一切正常,我可以毫无问题地下载。下面的代码在下载过程中也会更新我的进度条状态,没有任何问题。

我的问题:如何检测FTP站点不再可用/连接下载?监视ftp的单独线程isAvailible()和isConnected()方法即使关闭网络也总是返回true?

请参阅以下代码:

        // Disable the download button
        BTNdownload.setText("Downloading...");
        BTNdownload.setEnabled (false);

        // Create a instance of the FTP client
        ftpClient = new FTPClient();

        // Setup the FTP client         
        ftpClient.connect(server, port);
        ftpClient.login(user, pass);
        ftpClient.enterLocalPassiveMode();
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

        // Create a file in destination folder
        output = new File(destination);

        // Request the download file size
        ftpClient.sendCommand("SIZE", origin);

        // Get the size of the file
        String size = ftpClient.getReplyString().split(" ") [1].trim();           
        total = Long.parseLong(size);

        // Set the JProgressBar limits
        JPBprogress.setMinimum(0);
        JPBprogress.setMaximum((int) total/1024);

        // Enable the progress bar
        JPBprogress.setEnabled(true);

        // Create a input stream from the remote file
        stO = ftpClient.retrieveFileStream(origin);

        // Create a output stream to the output file
        OutputStream stD =  new BufferedOutputStream(new FileOutputStream(output));

        // Add a progress listener to the copy process
        org.apache.commons.net.io.Util.copyStream(stO, stD, ftpClient.getBufferSize(),  
                org.apache.commons.net.io.CopyStreamEvent.UNKNOWN_STREAM_SIZE,
                new org.apache.commons.net.io.CopyStreamAdapter() {
                    public void bytesTransferred(long totalBytesTransferred,
                            int bytesTransferred,
                            long streamSize) {

                            // Update the progress bar
                            JPBprogress.setValue((int) totalBytesTransferred/1024);    
                    }
        });

        // Close the input & output stream
        stO.close();
        stD.close ();

        // Send the FTP completed command
        ftpClient.completePendingCommand();

        // Close the connection
        ftpClient.abort();

        // Set the update button enabled
        BTNinstall.setEnabled(true);

1 个答案:

答案 0 :(得分:0)

您可以使用sendNoOp() ping ftp服务器,以便在长时间运行的下载中保持连接活动。