Ftp工具类

整理了Ftp的上传、下载、删除文件方便使用。

package com.xu.wrapper.utils;

import cn.hutool.core.util.StrUtil;
import com.xu.wrapper.exception.IException;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * ftp工具类
 * commons-net-3.3.jar
 * commons-io-2.4.jar
 * Author xuyl
 * Date 2019/6/1 14:54
 **/
@Component
public class FtpUtils {

    @Value("${javaUtilsConfig.ftpInfo.ip:#{null}}")
    public String ip;

    @Value("${javaUtilsConfig.ftpInfo.port:#{0}}")
    public int port;

    @Value("${javaUtilsConfig.ftpInfo.username:#{null}}")
    public String ftpUserName;

    @Value("${javaUtilsConfig.ftpInfo.password:#{null}}")
    public String ftpPassword;



    private static final Logger logger = LoggerFactory.getLogger(FtpUtils.class);

    /** 本地字符编码 */
    public static String SERVER_CHARSET = "UTF-8";//server-u上是GBK
    // FTP协议里面,规定文件名编码为iso-8859-1
    public static String TRANS_CHARSET = "ISO-8859-1";

    /**
     * 获取FTPClient对象
     * @return
     */
    public FTPClient getFTPClient() throws IException {
        try {
            FTPClient ftpClient;
            ftpClient = new FTPClient();
            ftpClient.connect(ip, port);
            ftpClient.login(ftpUserName, ftpPassword);
            if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                ftpClient.disconnect();
                throw new IException("未连接到FTP,用户名或密码错误。");
            }
            // 开启服务器对UTF-8的支持,如果服务器支持就用UTF-8编码,否则就使用本地编码(GBK).
            if (FTPReply.isPositiveCompletion(ftpClient.sendCommand("OPTS UTF8", "ON"))) {
                SERVER_CHARSET = "UTF-8";
            }else{
                SERVER_CHARSET = "GBK";
            }
            // 设置传输的模式
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftpClient.enterLocalPassiveMode();// 设置被动模式
            return ftpClient;
        } catch (IExceptione) {
            throw new IException(e.getMessage(), e);
        } catch (Exception e) {
            throw new IException("获取Ftp客户端失败", e);
        }
    }

    /**
     * 关闭ftp客户端
     * @param ftpClient
     */
    public void closeClient(FTPClient ftpClient) throws IException{
        if(ftpClient!=null){
            try {
                ftpClient.logout();
                ftpClient.disconnect();
            } catch (Exception e) {
                throw new IException("关闭客户端失败", e);
            }
        }
    }




    /**
     * 创建目录
     * @param ftpClient
     * @param list          目录名称
     * @throws IOException
     */
    public String createDirectory(FTPClient ftpClient, List<String> list) throws IException{
        try {
            StringBuilder ftpFilePath = new StringBuilder();
            for(String directory : list) {
                ftpFilePath.append(directory).append(System.getProperty("file.separator"));
                if(!createDirectory(ftpClient, directory)) {
                    throw new IException("Ftp创建目录失败!");
                }
            }
            //创建完成后跳转到根目录
            ftpClient.changeWorkingDirectory("/");
            return ftpFilePath.toString();
        } catch (Exception e) {
            throw new IException("Ftp创建目录失败!", e);
        }
    }
    private boolean createDirectory(FTPClient ftpClient, String directory) throws IOException {
        if(directoryIsExist(ftpClient, directory)) {
            ftpClient.changeWorkingDirectory(directory);
            return true;
        }
        if(ftpClient.makeDirectory(directory)) {
            ftpClient.changeWorkingDirectory(directory);
            return true;
        }
        return false;
    }
    private boolean directoryIsExist(FTPClient ftpClient, String directory) throws IOException {
        FTPFile[] ftpFiles = ftpClient.listDirectories();
        for (FTPFile ftpFile : ftpFiles) {
            if (directory.equals(ftpFile.getName())) {
                return true;
            }
        }
        return false;
    }


    /**
     *
     * @param ftpClient ftp对象
     * @param ftpFileDirectory   目录
     * @param ftpFileDirectory   文件名
     *
     * @param in        上传文件流
     */
    public Boolean uploadFile(FTPClient ftpClient, String ftpFileDirectory, String ftpFileName, InputStream in) throws IException{
        try {
            String ftpPath = ftpFileDirectory + ftpFileName;
            //更改ftp的操作文件目录,相当于获取操作对象
            ftpClient.changeWorkingDirectory(ftpPath);
            return ftpClient.storeFile(new String(ftpPath.getBytes(SERVER_CHARSET), TRANS_CHARSET), in);
        } catch (Exception e) {
            throw new IException("ftp文件上传失败", e);
        }
    }

    /**
     * ftp下载文件
     * @param ftpFilePath    文件所在的目录
     * @param ftpFilePath     文件名称
     * @return
     * @throws Exception
     */
    public InputStream downloadFile(FTPClient ftpClient, String ftpFilePath, String ftpFileName) throws IException{
        try {
            InputStream inputStream = null;
            //跳转到目录
            ftpClient.changeWorkingDirectory(ftpFilePath);
            FTPFile[] ftpFiles = ftpClient.listFiles();
            for (FTPFile file : ftpFiles) {
                String tempFileName = new String(file.getName().getBytes(TRANS_CHARSET), SERVER_CHARSET);
                if(tempFileName.equals(ftpFileName)){
                    inputStream = ftpClient.retrieveFileStream(file.getName());
                }
            }
            return inputStream;
        } catch (Exception e) {
            throw new IException("ftp文件下载失败", e);
        }
    }

    public void delFile(String filePath, String fileName) throws IException{
        try {
            FTPClient ftpClient = getFTPClient();
            ftpClient.changeWorkingDirectory(filePath);
            ftpClient.deleteFile(new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
            closeClient(ftpClient);
        } catch (Exception e) {
            throw new IException("ftp文件删除失败", e);
        }
    }

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值