Ftp in java

By | July 18, 2015
Share the joy
  •  
  •  
  •  
  •  
  •  
  •  

Below code download file from ftp server:

package ftp;

import org.apache.commons.net.ftp.FTPClient;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import org.apache.commons.net.PrintCommandListener;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPReply;


/**
 * Created by pli on 7/16/2015.
 */

public class FtpDownloader {

    FTPClient ftp = null;

    public FtpDownloader(String host, String user, String pwd) throws Exception {
        ftp = new FTPClient();
        ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
        int reply;
        ftp.connect(host);
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            throw new Exception("Exception in connecting to FTP Server");
        }
        ftp.login(user, pwd);
        ftp.setFileType(FTP.BINARY_FILE_TYPE);
        ftp.enterLocalPassiveMode();
    }

    public void downloadFile(String remoteFilePath, String localFilePath) {
        try  {
            FileOutputStream fos = new FileOutputStream(localFilePath);
            this.ftp.retrieveFile(remoteFilePath, fos);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void disconnect() {
        if (this.ftp.isConnected()) {
            try {
                this.ftp.logout();
                this.ftp.disconnect();
            } catch (IOException f) {
                // do nothing as file is already downloaded from FTP server
            }
        }
    }

    public static void main(String[] args) {
        try {
            FtpDownloader ftpDownloader = new FtpDownloader("127.0.0.1", "pli", "pli");
            ftpDownloader.downloadFile("/tmp/1.java", "/home/2.txt");
            ftpDownloader.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

pom.xml dependency:

<dependency>
    <groupId>org.springframework.integrationgroupId>
    <artifactId>spring-integration-sftpartifactId>
    <version>4.1.6.RELEASEversion>
dependency>