FTPing files with Java

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();
    }
}

Did you like my blog post?

Signup now and receive an email when I publish new luv2code content.

I agree to have my personal information transfered to AWeber ( more information )

I will never give away, trade or sell your email address. You can unsubscribe at any time.

Leave a Reply