FTPUtil - upload and download

1 篇文章 0 订阅
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;
import org.spockframework.util.TimeUtil;

import java.io.*;

/**
 *
 * FTP Util
 *
 * @author 
 * @date 2019-12-23
 */
public class FTPUtils {


    private final static Logger log = Logger.getLogger(FTPUtils.class);

    private  String path ;

    private String host;

    private int port;

    private String username;

    private String password;

    private FTPClient client;

    /**
     * Constructor Initialie configuration
     *
     * @param host
     * @param port
     * @param username
     * @param password
     */
    public FTPUtils(String host, int port, String username, String password,String path) {

        this.host = host;
        this.port = port;
        this.username = username;
        this.password = password;
        this.path = path;
        openClient();
    }

    /**
     *  Open connect
     *
     *
     */
    private void openClient(){

        try {
            log.info(" Enter open client method ...");
            log.info(" FTP configuration : host {"+host+"}, port {"+port+"}, username {"+username+"}, password {"+password+"} ");

            client = new FTPClient();
            //1 . Set the connection properties
            client.setConnectTimeout(5000);
            client.setControlEncoding("UTF-8");
//            client.enterLocalActiveMode();

            //2. Use the host and port to connect the server, and log in
            log.info(" Use the host and port to connect the server ....");
            client.connect(this.host, this.port);

            log.info(" Log in the FTP server .....");
            client.login(this.username, this.password);

            //3.Check the connection status
            log.info(" Check the connection status");
            if(!FTPReply.isPositiveCompletion(client.getReplyCode())){

                log.error(" FTP connect failed!");
                log.info(" FTP  disconnect ....");
                client.disconnect();
                log.info(" FTP  disconnect success!!!");

            }else{
                log.info(" FTP connect success!!!!");
            }
        }catch (Exception e){
           log.error(" FTP connect  exception: {}!",e);
        }
    }

    /**
     * closeClient
     */
    public void closeClient(){
        try {
            client.logout();
        }catch (Exception e){
            log.error(" FTP close failed  exception: {}!", e);
        }finally {
            if(client.isConnected()){
                try {
                    client.disconnect();
                } catch (IOException e) {
                    log.error(" FTP close failed  exception: {}!", e);
                }
            }
        }
    }




    /**
     * Download File
     *
     * @param serverPath Files in the path of the server
     * @param savePath   Files saved local position
     * @param fileName   name
     */
    public boolean downloadFile(String serverPath, String savePath, String fileName){
        boolean downFlag = false;
        try {
            /**1.The Find files **/
            client.enterLocalPassiveMode();
            /**2. change work directory **/
            client.changeWorkingDirectory(serverPath);

            /**3.Find files **/
            for(FTPFile file:client.listFiles()){
                if(fileName.equals(file.getName())){
                    /** 4.Save the path **/
                    OutputStream saveFile = new FileOutputStream(new File(savePath + File.separator + fileName));
                    client.retrieveFile(new String(file.getName().getBytes("UTF-8"),"ISO-8859-1"), saveFile);
                    downFlag = true;
                }
            }
        }catch (Exception e){
            log.error(" Download failed exception: {}!",e);
        }
        return downFlag;
    }



    /**
     * Upload File
     *
     *  @param serverPath Files in the path of the server
     *  @param file   Files saved local position
     *
     *  @return Boolean
     */
    public Boolean uploadFile(String serverPath, File file){
        log.info(" Enter upload File method ....");
        log.info(" Config detail {} "+ toString());

        try {

            client.enterLocalPassiveMode();
            client.setFileType(FTPClient.BINARY_FILE_TYPE);
            client.setControlEncoding("UTF-8");
            
            /** Create folder **/
            if(!client.changeWorkingDirectory(serverPath)){
                log.info(" Create folder");
                client.makeDirectory(serverPath);
                client.changeWorkingDirectory(serverPath);
            }

            /** Upload file **/
            log.info(" filePath {} "+ file.getPath() +" fileName {} "+ file.getName());

            Boolean flag = client.storeFile("/" + file.getName(), new FileInputStream(file));

            if (flag == true){
                log.info(" DWH upload file success !!!!! ");
                return true;
            }



        }catch (Exception e){
            log.error(" Upload failed exception: {}!", e);
        }
        return false;
    }





    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    @Override
    public String toString() {
        return "FTPUtils{" +
                "path='" + path + '\'' +
                ", host='" + host + '\'' +
                ", port=" + port +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", client=" + client +
                '}';
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值