On my last project, we had a requirement to send a file to an FTP server. We’ve all used FTP servers at some point in time. However, I never had to access an FTP via Java code. After a quick Google search, I came across the Jakarta Commons NET package. This package provides a collection of network related classes for FTP, Telnet, POP3, etc…

It didn’t take much work to add FTP support. I simply downloaded the JAR file from the Jakarta Commons NET website.

And then I dropped in this sample code:

package com.luv2code.ftp;

import java.io.FileInputStream;
import java.io.InputStream;
import org.apache.commons.net.ftp.*;

/**
 *
 * @author Chad Darby
 */
public class FtpUtils {

    public void send(String ftpServer, String userName, String password, String theFileName) {

        // connect to server
        FTPClient ftp = new FTPClient();
        ftp.connect(server);

        if (!ftp.login(userName, password)) {
            ftp.logout();
        }

        int reply = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
        }

        // send a file
        InputStream input = new FileInputStream(theFileName);
        ftp.setFileType(ftp.BINARY_FILE_TYPE);
        boolean success = ftp.storeFile("temp.txt", input);

        // clean up
        input.close();
        ftp.logout();
        ftp.disconnect();
    }
}