Glass Onion Blog

Cheat sheets, post-its and random notes from the desk of a programmer

Posts Tagged ‘ftp’

FTP file transfer in Java using Apache Commons Net

Posted by walrus on July 17, 2008

The following sample code works well with Java 1.5 and Apache Commons Net 1.4.1


import org.apache.commons.net.ftp.*;
...
boolean ftpTransfer(String localfile, String destinationfile)
{
	String server = "ftp.domain.com";
	String username = "ftpuser";
	String password = "ftppass";
	try
	{
		FTPClient ftp = new FTPClient();
		ftp.connect(server);
		if(!ftp.login(username, password))
		{
			ftp.logout();
			return false;
		}
		int reply = ftp.getReplyCode();
		if (!FTPReply.isPositiveCompletion(reply))
		{
			ftp.disconnect();
			return false;
		}
		InputStream in = new FileInputStream(localfile);
		ftp.setFileType(ftp.BINARY_FILE_TYPE);
		boolean Store = ftp.storeFile(destinationfile, in);
		in.close();
		ftp.logout();
		ftp.disconnect();
	}
	catch (Exception ex)
	{
		ex.printStackTrace();
		return false;
	}
	return true;
}
 

Posted in Apache, Software, Technology, java | Tagged: , , , | Leave a Comment »