ftp工具类(不支持sftp)

package com.lianlian.cbfin.chnlgw.risk.common.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSON;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

import com.lianlian.cbfin.chnlgw.yintong.api.common.enums.ResultCodeEnum;
import com.lianlian.cbfin.chnlgw.yintong.common.exception.BizException;

import lombok.extern.slf4j.Slf4j;


@Slf4j
public class FtpUtils {

    private String host;

    private Integer port;

    private String username;

    private String password;

    private Integer timeout;

    private static FtpUtils ftpUtils;

    private FtpUtils(){}

    private FtpUtils(String host, Integer port, String username, String password, Integer timeout) {
        this.host = host;
        this.port = port;
        this.password = password;
        this.username = username;
        this.timeout = timeout;
    }

    public static FtpUtils getInstance(String host, Integer port, String username, String password, Integer timeout) {
        if(ftpUtils == null) {
            ftpUtils = new FtpUtils(host, port, username, password, timeout);
        }
        return ftpUtils;
    }

    private FTPClient getFTPClient() {
        FTPClient ftpClient = null;
        try {
            ftpClient = new FTPClient();
            // 设置中文编码集,防止中文乱码
            ftpClient.setControlEncoding("UTF-8");
            // 连接FPT服务器,设置IP及端口
            ftpClient.connect(host, port);
            // 设置用户名和密码
            ftpClient.login(username, password);
            // 设置连接超时时间
            ftpClient.setConnectTimeout(timeout);
            // 防止大文件下载超时
            ftpClient.setControlKeepAliveReplyTimeout(5000);
            ftpClient.setControlKeepAliveTimeout(15);
            ftpClient.setSoTimeout(60000);
            ftpClient.setDataTimeout(3600 * 1000);
            // 是否成功登录
            if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                log.info("未连接到FTP,用户名或密码错误");
                ftpClient.disconnect();
            } else {
                log.info("FTP连接成功");
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return ftpClient;
    }

    public List<String> getFileNameList(String ftpPath) {
        FTPClient ftpClient = null;
        try {
            log.info("从ftp目录{}获取文件列表", ftpPath);
            ftpClient = getFTPClient();
            //切换FTP目录
            ftpClient.changeWorkingDirectory(ftpPath);
            ftpClient.enterLocalPassiveMode();
            FTPFile[] ftpFiles = ftpClient.listFiles();
            List<String> dfsFileNames = Arrays.stream(ftpFiles).map(FTPFile::getName).collect(Collectors.toList());
            log.info("从ftp目录{}获取文件列表成功,文件列表{}", ftpPath, JSON.toJSONString(dfsFileNames));

            ftpClient.logout();
            return dfsFileNames;
        } catch (Exception e) {
            log.error("获取文件列表异常,异常信息:{}", e.getMessage());
            throw new BizException(ResultCodeEnum.DOWNLOAD_FILE_ERROR, e.getMessage());
        } finally {
            if (ftpClient != null && ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    log.error("获取文件列表异常,异常信息:{}", e.getMessage(), e);
                }
            }
        }
    }

    /**
     * 下载文件
     * @param ftpPath ftp文件目录
     * @param fileName 文件名称
     * @param localPath 本地目录
     * @return
     */
    public boolean downloadFile(String ftpPath, String fileName, String localPath) {
        OutputStream os = null;
        FTPClient ftpClient = null;
        try {
            boolean flag = false;
            //创建本地目录
            File dir = new File(localPath);
            if (!dir.exists()) {
                dir.mkdir();
            }
            log.info("从ftp目录{}开始下载文件{}到{}", ftpPath, fileName, localPath);
            ftpClient = getFTPClient();
            //切换FTP目录
            ftpClient.changeWorkingDirectory(ftpPath);
            ftpClient.enterLocalPassiveMode();
            FTPFile[] ftpFiles = ftpClient.listFiles();
            for(FTPFile file : ftpFiles){
                if(fileName.equalsIgnoreCase(file.getName())){
                    File localFile = new File(localPath + File.separator + file.getName());
                    os = new FileOutputStream(localFile);
                    ftpClient.retrieveFile(file.getName(), os);
                    os.flush();
                    os.close();
                    flag = true;
                }
            }
            ftpClient.logout();
            if(flag) {
                log.info("{}下载文件成功", fileName);
            }
            else {
                log.info("在{}下找不到{}文件", ftpPath, fileName);
                throw new BizException(ResultCodeEnum.NOT_FOUND_FILE);
            }
        } catch (Exception e) {
            log.error("下载文件异常,异常信息:{}", e.getMessage());
            throw new BizException(ResultCodeEnum.DOWNLOAD_FILE_ERROR, e.getMessage());
        } finally {
            if(os != null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(ftpClient != null) {
                if(ftpClient.isConnected()){
                    try{
                        ftpClient.disconnect();
                    }catch(IOException e){
                        e.printStackTrace();
                    }
                }
            }
        }

        return true;
    }

    /**
     * 上传文件
     * @param ftpPath ftp文件目录
     * @param fileName 文件名称
     * @param localPath 待上传文件目录
     * @return
     */
    public boolean uploadFile(String ftpPath, String fileName, String localPath) throws Exception{
        log.info("从{}开始上传文件{}到ftp目录{}", localPath, fileName, ftpPath);
        FTPClient ftpClient = null;
        InputStream is = null;
        boolean flag = false;
        try {
            ftpClient = getFTPClient();
            ftpClient.enterLocalPassiveMode();
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            //判断FPT目标文件夹是否存在不存在则创建
            if(!ftpClient.changeWorkingDirectory(ftpPath)){
                ftpClient.makeDirectory(ftpPath);
            }
            //切换FTP目录
            ftpClient.changeWorkingDirectory(ftpPath);
            //上传文件
            is = new FileInputStream(new File(localPath + File.separator + fileName));
            String tempName = ftpPath + "/" + fileName;
            flag = ftpClient.storeFile(new String(tempName.getBytes("UTF-8"),"ISO-8859-1"), is);
            if(flag){
                log.info("上传文件成功");
            }else{
                log.error("上传文件失败");
            }
        } catch (Exception e) {
            log.error("上传文件异常,异常信息:{}", e.getMessage());
            throw new BizException(ResultCodeEnum.UPLOAD_FILE_ERROR, e.getMessage());
        } finally {
            if(is != null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(ftpClient != null) {
                if(ftpClient.isConnected()){
                    try{
                        ftpClient.disconnect();
                    }catch(IOException e){
                        e.printStackTrace();
                    }
                }
            }
        }

        return flag;
    }

    /**
     * 下载文件--通过断点续传方式
     * @param ftpPath ftp文件目录
     * @param fileName 文件名称
     * @param localPath 本地目录
     * @return
     */
    public boolean downloadFileByBreakPoint(String ftpPath, String fileName, String localPath) {
        OutputStream os = null;
        InputStream in = null;
        FTPClient ftpClient = getFTPClient();
        try {
            boolean flag = false;
            //创建本地目录
            File dir = new File(localPath);
            if (!dir.exists()) {
                dir.mkdir();
            }
            //需要下载到本地目录的文件大小
            long localFileLength = 0;
            File localFile = new File(localPath + File.separator + fileName);
            if (localFile.exists()) {
                localFileLength = localFile.length();
            }

            log.info("从ftp目录{}开始下载文件{}到{}", ftpPath, fileName, localPath);
            //切换FTP目录
            ftpClient.changeWorkingDirectory(ftpPath);
            ftpClient.enterLocalPassiveMode();
            FTPFile[] ftpFiles = ftpClient.listFiles();
            for(FTPFile file : ftpFiles){
                if(fileName.equalsIgnoreCase(file.getName())){
                    if (file.getSize() <= localFileLength) {
                        return true;
                    }
                    os = new FileOutputStream(localFile, true);
                    ftpClient.setRestartOffset(localFileLength); //断点位置
                    in = ftpClient.retrieveFileStream(((new String(fileName.getBytes("UTF-8"), "iso-8859-1"))));
                    byte[] bytes = new byte[5120];
                    int c;
                    while ((c = in.read(bytes)) != -1) {
                        os.write(bytes, 0, c);
                    }
                    os.flush();
                    flag = true;
                }
            }
            if(flag) {
                log.info("{}下载文件成功", fileName);
            }
            else {
                log.info("在{}下找不到{}文件", ftpPath, fileName);
                throw new BizException(ResultCodeEnum.NOT_FOUND_FILE);
            }
        } catch (Exception e) {
            log.error("下载文件异常,异常信息:{}", e.getMessage(), e);
            throw new BizException(ResultCodeEnum.DOWNLOAD_FILE_ERROR, e.getMessage());
        } finally {
            if(in != null){
                try {
                    in.close();
                    ftpClient.completePendingCommand();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(os != null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(ftpClient != null) {
                if(ftpClient.isConnected()){
                    try{
                        ftpClient.disconnect();
                    }catch(IOException e){
                        e.printStackTrace();
                    }
                }
            }
        }
        log.info("下载文件流程结束");
        return true;
    }


    public void deleteFile(String ftpPath, String fileName) {
        log.info("从ftp目录{}开始删除文件{}", ftpPath, fileName);
        FTPClient ftpClient = null;
        boolean flag;
        try {
            ftpClient = getFTPClient();
            ftpClient.enterLocalPassiveMode();
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

            //切换FTP目录
            ftpClient.changeWorkingDirectory(ftpPath);
            flag = ftpClient.deleteFile(ftpPath + fileName);
            if (flag) {
                log.info("删除文件成功");
            } else {
                log.error("删除文件失败");
            }
        } catch (Exception e) {
            log.error("删除文件异常,异常信息:{}", e.getMessage());
            throw new BizException(ResultCodeEnum.UPLOAD_FILE_ERROR, e.getMessage());
        } finally {
            if (ftpClient != null && ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    log.error("删除文件异常,异常信息:{}", e.getMessage(), e);
                }
            }
        }
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值