Using Apache commons Net FTP Client
- By Shoukri Kattan
- 17 August, 2011
- No Comments
Do you need an FTP client to use from within your Java application, to connect to, upload and download files from FTP server.
One of the best that I have been using for the last few years is Apache’s common net FTP clientÂ
Here is a quick and dirty sample code to get you started. Of course Apache have more examples that you can see when you download the source code.
protected boolean ftpFile(String server, String username, String password,
File localFile, String remoteDir) {
try {
FTPClient ftp = new FTPClient();
ftp.connect(server);
if (!ftp.login(username, password)) {
System.err.println("Login failed to FTP server");
ftp.logout();
return false;
}
int reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
System.err
.println("Did not receive positive reply after login to FTP server");
ftp.disconnect();
return false;
}
InputStream in = new FileInputStream(localFile);
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
boolean Store = ftp.storeFile(
remoteDir + "/" + localFile.getName(), in);
in.close();
ftp.logout();
ftp.disconnect();
return Store;
} catch (Exception ex) {
System.err.println("Error while trying to FTP file to server");
ex.printStackTrace();
return false;
}
}
