In my earlier article, I have shown you how to upload a document into the ftp server. Here is the code to download a file from ftp server.
Jars required: commons-net-1.4.1.jar
Can be downloaded from: http://commons.apache.org/net/download_net.cgi
import java.io.FileOutputStream;
import java.io.OutputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
public class DownloadFromFtp {
public static void main(String[] args) {
DownloadFromFtp downloadFTP = new DownloadFromFtp();
downloadFTP.downloadFromFTP();
}
private void downloadFromFTP() {
try {
FTPClient ftpClient = new FTPClient();
// This is the file name to be downloaded
String fileName = "demo.txt";
// This is the ftp server details to be connected
ftpClient.connect("ftpserverlocation");
int replyCode = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(replyCode)) {
System.out.println("Server DOwn");
}
// Credentials to login into the ftp server.
boolean login = ftpClient.login("username", "password");
// A particular directory where the file exists
boolean changeWorkingDirectory = ftpClient
.changeWorkingDirectory("ftpdirectory");
boolean setFileType = ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
OutputStream data = (OutputStream) new FileOutputStream(fileName);
// Actually retrieving the file
ftpClient.retrieveFile(fileName, data);
} catch (Exception e) {
e.printStackTrace();
}
}
}
No comments:
Post a Comment