FTP上传下载工具类(应急,过两天完善)

package com.jxxgt.ftpdemo.utils;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 咦!一只菜鸡
 * @date 2021/5/30 10:11
 * @className FtpUtils
 * @description ftp工具类
 */
@Component
@PropertySource("classpath:ftp.properties")
public class FtpUtils {
    @Value("${ftp.host}")
    private String ftpHost;
    @Value("${ftp.port}")
    private int ftpPort;
    @Value("${ftp.username}")
    private String ftpUsername;
    @Value("${ftp.password}")
    private String ftpPassword;

    private FTPClient ftpClient;


    public static final char SLASH = '/';
    public static final char BACKSLASH = '\\';

    public boolean init(){
        return init(ftpHost,ftpPort,ftpUsername,ftpPassword);
    }

    /**
     * 初始化连接
     *
     * @return this
     */
    public boolean init(String ftpHost,int ftpPort,String ftpUsername,String ftpPassword) {
        final FTPClient client = new FTPClient();
        client.setControlEncoding("UTF-8");
        try {
            // 连接ftp服务器
            client.connect(ftpHost, ftpPort);
            // 登录ftp服务器
            client.login(ftpUsername, ftpPassword);
        } catch (IOException e) {
//            throw new FtpException(e);
        }
        final int replyCode = client.getReplyCode(); // 是否成功登录服务器
        if (false == FTPReply.isPositiveCompletion(replyCode)) {
            try {
                client.disconnect();
                return false;
            } catch (IOException e) {
                // ignore
            }
        }
        ftpClient = client;
        return true;
    }

    /**
     * 改变目录
     *
     * @param directory 目录
     * @return 是否成功
     */
    public boolean cd(String directory) {
        boolean flag = true;
        try {
            flag = ftpClient.changeWorkingDirectory(directory);
        } catch (IOException e) {
//            throw new FtpException(e);
        }
        return flag;
    }

    /**
     * 远程当前目录
     *
     * @return 远程当前目录
     * @since 4.1.14
     */
    public String pwd() {
        try {
            return ftpClient.printWorkingDirectory();
        } catch (IOException e) {
//            throw new FtpException(e);
        }
        return "";
    }

    public List<String> ls(String path) {
        final FTPFile[] ftpFiles = lsFiles(path);

        final List<String> fileNames = new ArrayList<>();
        for (FTPFile ftpFile : ftpFiles) {
            fileNames.add(ftpFile.getName());
        }
        return fileNames;
    }

    /**
     * 遍历某个目录下所有文件和目录,不会递归遍历
     *
     * @param path 目录
     * @return 文件或目录列表
     */
    public FTPFile[] lsFiles(String path){
        String pwd = null;
        if(!StringUtils.isEmpty(path)) {
            pwd = pwd();
            cd(path);
        }

        try {
            FTPFile[] ftpFiles = ftpClient.listFiles();

            if(!StringUtils.isEmpty(pwd)) {
                // 回到原目录
                cd(pwd);
            }
            return ftpFiles;
        } catch (IOException e) {
//            throw new FtpException(e);
        }
        return null;
    }


    public boolean mkdir(String dir) {
        boolean flag = true;
        try {
            flag = ftpClient.makeDirectory(dir);
        } catch (IOException e) {
//            throw new FtpException(e);
        }
        return flag;
    }

    /**
     * 判断ftp服务器文件是否存在
     *
     * @param path 文件路径
     * @return 是否存在
     */
    public boolean existFile(String path) {
        FTPFile[] ftpFileArr = new FTPFile[0];
        try {
            ftpFileArr = ftpClient.listFiles(path);
        } catch (IOException e) {
//            throw new FtpException(e);
        }
        if (ftpFileArr!=null&&ftpFileArr.length!=0) {
            return true;
        }
        return false;
    }
    /**
     * 创建指定文件夹及其父目录,从根目录开始创建,创建完成后回到默认的工作目录
     *
     * @param dir 文件夹路径,绝对路径
     */
    public void mkDirs(String dir) {
        final String[] dirs = dir.trim().split("[\\\\/]+");

        final String now = pwd();
        if(dirs.length > 0 && StringUtils.isEmpty(dirs[0])) {
            //首位为空,表示以/开头
            this.cd(String.valueOf(SLASH));
        }
        for (int i = 0; i < dirs.length; i++) {
            if (!StringUtils.isEmpty(dirs[i])) {
                if (false == cd(dirs[i])) {
                    //目录不存在时创建
                    mkdir(dirs[i]);
                    cd(dirs[i]);
                }
            }
        }
        // 切换回工作目录
        cd(now);
    }

    /**
     * 设置FTP连接模式,可选主动和被动模式
     *
     * @param mode 模式枚举
     * @return this
     * @since 4.1.19
     */
    public void setMode(String mode) {
        switch (mode) {
            case "Active":  // 主动模式
                ftpClient.enterLocalActiveMode();
                break;
            case "Passive": // 被动模式
                ftpClient.enterLocalPassiveMode();
                break;
        }
    }



    /**
     * 上传文件到指定目录,可选:
     *
     * <pre>
     * 1. path为null或""上传到当前路径
     * 2. path为相对路径则相对于当前路径的子路径
     * 3. path为绝对路径则上传到此路径
     * </pre>
     *
     *
     * @param path 服务端路径,可以为{@code null} 或者相对路径或绝对路径
     * @param fileName 文件名
     * @param fileStream 文件流
     * @return 是否上传成功
     */
    public boolean upload(String path, String fileName, InputStream fileStream) {
        try {
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            if(!StringUtils.isEmpty(path)) {
                mkDirs(path);
                boolean isOk = cd(path);
                if(false == isOk) {
                    return false;
                }
            }
            return ftpClient.storeFile(fileName, fileStream);
        } catch (IOException e) {
//            throw new FtpException(e);
        }
        return false;
    }


    /**
     * 下载文件到输出流
     *
     * @param path 文件路径
     * @param fileName 文件名
     * @param out 输出位置
     */
    public void download(String path, String fileName, OutputStream out) {
        cd(path);
        try {
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftpClient.retrieveFile(fileName, out);
        } catch (IOException e) {
//
        }
    }


    public static void main(String[] args) throws FileNotFoundException {
        FtpUtils ftpUtils = new FtpUtils();
        ftpUtils.init("192.168.31.178",21,"ftpUser","jchw1993");
        String ftpPath = "/aa";   // ftp文件所在文件夹
        // 上传
        String fileNameUp = "aaa.zip";
        String uploadPath = "D:\\file\\form\\1200401409\\1591235671852.zip";
        ftpUtils.setMode("Passive");
        File fileUp = new File(uploadPath);
        ftpUtils.upload(ftpPath,fileNameUp,new FileInputStream(fileUp));

        // 下载
//        String fileName = "test2.txt"; // ftp目录中需要下载的文件名
//        String dirPath = "D:\\file\\download\\newFile.txt";
//        File file = new File(dirPath);
//        System.out.println(file.exists());
//        OutputStream out = new FileOutputStream(file);
//        ftpUtils.download(ftpPath,"test2.txt",out);

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

咦!一只菜鸡

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值