FTP工具類

灬點點發表於2020-09-29

一、依賴

        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.1.1</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.52</version>
        </dependency>

二、程式碼

import cn.hutool.extra.ftp.Ftp;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Slf4j
@Component
public class FTPUtil {

    private static String host;
    private static Integer port;
    private static String user;
    private static String pwd;

    @Value("${ftp.host}")
    public void setHost(String host) {
        FTPUtil.host = host;
    }

    @Value("${ftp.port}")
    public void setPort(Integer port) {
        FTPUtil.port = port;
    }

    @Value("${ftp.user}")
    public void setUser(String user) {
        FTPUtil.user = user;
    }

    @Value("${ftp.pwd}")
    public void setPwd(String pwd) {
        FTPUtil.pwd = pwd;
    }


    /**
     * 建立ftp連線
     **/
    public static Ftp create() {
        Ftp ftp = null;
        try {
            port = Objects.isNull(port) ? Ftp.DEFAULT_PORT : port;
            ftp = StringUtils.isEmpty(user) && StringUtils.isEmpty(pwd)
                    ? new Ftp(host, port)
                    : new Ftp(host, port, user, pwd);
        }catch (Exception e){
            log.error("建立ftp連結失敗:{}",e);
        }
        if (ftp == null) {
            throw new RuntimeException("連線FTP伺服器失敗,請檢查配置是否正確");
        }
        //防止客戶端讀取檔案為空
        ftp.getClient().enterLocalPassiveMode();
        return ftp;
    }


    /**
     * ftp檔案批量下載
     **/
    public static List<File> download(Ftp ftp, String path) {
        try {
            List<File> files = new ArrayList<>();
            ftp.cd(path);
            List<String> ftpFiles = ftp.ls(ftp.pwd());
            log.info("檔案列表為{}", JSON.toJSONString(ftpFiles));
            if (!CollectionUtils.isEmpty(ftpFiles)) {
                ftpFiles.stream().forEach(e->{
                    //新建檔案
                    File file = new File(e);
                    if (!file.exists()) {
                        if (!Objects.isNull(file.getParentFile()) &&
                                !file.getParentFile().exists()) {
                            file.getParentFile().mkdirs();
                        }
                        try {
                            file.createNewFile();
                        } catch (IOException ex) {
                            log.error("建立檔案異常:{}",e);
                        }
                    }
                    ftp.download(path, e, file);
                    files.add(file);
                });
                return files;
            }
        } catch (Exception e) {
            log.error("批量下載檔案異常:{}",e);
        }
        return null;
    }

    /**
     * ftp檔案上傳
     **/
    public static boolean upload(Ftp ftp, String fileName, String path, File file) {
        if (StringUtils.isEmpty(path)) {
            return false;
        }
        if (!ftp.exist(path)) {
            ftp.mkdir(path);
        }
        ftp.upload(path, fileName, file);
        ftp.toParent();
        return true;
    }

    /**
     * 上傳InputStream檔案
     **/
    public static boolean uploadRecord(Ftp ftp, String fileName, String path, InputStream inputStream) {
        try {
            if (!ftp.exist(path)) {
                ftp.mkDirs(path);
            }
            // 目錄存在開始上傳
            if (ftp.exist(path)) {
                ftp.upload(path, fileName, inputStream);
            }
        } catch (Exception e) {
            log.error("檔案上傳失敗: {}",e);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                   log.error("關閉InputStream失敗:{}", e);
                }
            }
            close(ftp);
        }
        return true;
    }


    /**
     * 關閉ftp連線
     **/
    public static void close(Ftp ftp) {
        try {
            if (!Objects.isNull(ftp)) {
                ftp.close();//斷開連線
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

相關文章