Reputation: 79
I am working on a simple piece of java code for transferring a file from an HTTP site to the local machine. All works well and I can download without any problem. The code below updates my progress bar status during the download also without any problem.
My Question: How do I detect that the FTP site is no longer available/connected wile downloading? A separate thread monitoring the ftp isAvailible () and isConnected () methods always returns true even with the network switched off?
Please see code below:
// 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);
Upvotes: 0
Views: 871
Reputation: 3311
You can use sendNoOp() to ping the ftp server in order to keep the connection alive on a long running download.
Upvotes: 0