Java FTP Program
Java FTP Program
Login ftp server with configured username and passwordLocalPassiveMode switches data connection mode from server-to-client to client-to-server
Specified a remote server directory path that uses download files from the server
Download file from the ftp server
Java Code:
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
public class FtpFileDownload{
public static void main(String[] args) {
String serverAddress = "www.ftpserveraddress.com"; // ftp server address
int port = 21; // ftp uses default port Number 21
String username = "xyz";// username of ftp server
String password = "xyz"; // password of ftp server
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(serverAddress, port);
ftpClient.login(username,password);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE/FTP.ASCII_FILE_TYPE);
String remoteFilePath = "/filename.txt";
File localfile = new File("E:/ftpServerFile.txt");
OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(localfile));
boolean success = ftpClient.retrieveFile(remoteFilePath, outputStream);
outputStream.close();
if (success) {
System.out.println("Ftp file successfully download.");
}
} catch (IOException ex) {
System.out.println("Error occurs in downloading files from ftp Server : " + ex.getMessage());
} finally {
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
Comments
Post a Comment
Thanks for your Comments.