This tutorial contains description of file downloading from the FTP server using java.
Download File : FTPClient class supplies method to download files from FTP Server computer to the local/remote. We need another class FileOutputStream to handle the file during the transfer.
Here we are using retrieveFile(String remoteFile, OutputStream local) method. It throws FTPConnectionClosedException, CopyStreamException and IOException. This method is of boolean type and returns true if successfully downloaded otherwise returns false.
Example :
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPConnectionClosedException;
class FtpDownloadFile {
public static void main(String[] args) throws IOException {
FTPClient client = new FTPClient();
FileOutputStream fos = null;
boolean result;
try {
client.connect("localhost");
result = client.login("admin", "admin");
if (result == true) {
System.out.println("Successfully logged in!");
} else {
System.out.println("Login Fail!");
return;
}
String fileName = "test.txt";
fos = new FileOutputStream(fileName);
// Download file from the ftp server
result = client.retrieveFile(fileName, fos);
if (result == true) {
System.out.println("File is downloaded successfully!");
} else {
System.out.println("File downloading failed!");
}
client.logout();
} catch (FTPConnectionClosedException e) {
e.printStackTrace();
} finally {
try {
if (fos != null) {
fos.close();
}
client.disconnect();
} catch (FTPConnectionClosedException e) {
System.out.println(e);
}
}
}
}
Output :
Successfully logged in! File is downloaded successfully!
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.
Ask Questions? Discuss: FTP Server : Download file
Post your Comment