FTP工具类

一、依赖

        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.3.10</version>
        </dependency>

        <dependency>
            <groupId>commons-net</groupId>
            <artifactId>commons-net</artifactId>
            <version>3.6</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();
        }
    }

}
©️2020 CSDN 皮肤主题: 书香水墨 设计师:CSDN官方博客 返回首页