java FtpUtils 自用

maven依赖

<dependency>
     <groupId>commons-net</groupId>
     <artifactId>commons-net</artifactId>
     <version>3.6</version>
</dependency>
package xxxxxx.xxxx.xxxxx;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

import java.io.*;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Objects;

/**
 * @ClassName FtpUtils
 * @Description: TODO
 * @Version: 1.0
 * @Author: hz20126005
 * @Date: 2021/8/26 15:44
 */
@Slf4j
public class FtpUtils {

    private static final String XLS = ".xls";

    /**
     * 获取FTPClient对象
     * @param ftpHost 服务器IP
     * @param ftpPort 服务器端口号
     * @param ftpUserName 用户名
     * @param ftpPassword 密码
     * @return FTPClient
     */
    public static FTPClient getFtpClient(String ftpHost, int ftpPort, String ftpUserName, String ftpPassword) {
        FTPClient ftp = null;
        try {
            ftp = new FTPClient();
            // 连接FPT服务器,设置IP及端口
            ftp.connect(ftpHost, ftpPort);
            // 设置用户名和密码
            ftp.login(ftpUserName, ftpPassword);
            // 设置连接超时时间,5000毫秒
            ftp.setConnectTimeout(50000);
            // 设置中文编码集,防止中文乱码
            ftp.setControlEncoding("UTF-8");
            //避免无法读取目录的问题
            ftp.enterLocalPassiveMode();
            if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                log.info("未连接到FTP,用户名或密码错误");
                ftp.disconnect();
            } else {
                log.info("FTP连接成功");
            }

        } catch (SocketException e) {
            e.printStackTrace();
            log.info("FTP的IP地址可能错误,请正确配置");
        } catch (IOException e) {
            e.printStackTrace();
            log.info("FTP的端口错误,请正确配置");
        }
        return ftp;
    }

    /**
     * 关闭FTP方法
     * @param ftp ftp连接
     * @return boolean
     */
    public static boolean closeFtp(FTPClient ftp){
        try {
            ftp.logout();
        } catch (Exception e) {
            log.error("FTP关闭失败");
        }finally{
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                    log.error("FTP关闭失败");
                }
            }
        }
        return false;
    }


    /**
     * 下载FTP下指定文件
     * @param ftp FTPClient对象
     * @param filePath FTP文件路径
     * @param fileName 文件名
     * @param downPath 下载保存的目录
     * @return boolean
     */
    public static boolean downloadFtp(FTPClient ftp, String filePath, String fileName, String downPath) {
        // 默认失败
        boolean flag = false;

        try {
            // 跳转到文件目录
            ftp.changeWorkingDirectory(filePath);
            // 获取目录下文件集合
            ftp.enterLocalPassiveMode();
            FTPFile[] files = ftp.listFiles();
            for (FTPFile file : files) {
                // 取得指定文件并下载
                if (file.getName().equals(fileName)) {
                    File downFile = new File(downPath + File.separator
                            + file.getName());
                    OutputStream out = new FileOutputStream(downFile);
                    // 绑定输出流下载文件,需要设置编码集,不然可能出现文件为空的情况
                    flag = ftp.retrieveFile(new String(file.getName().getBytes(StandardCharsets.UTF_8),StandardCharsets.ISO_8859_1), out);
                    // 下载成功删除文件,看项目需求
                    // ftp.deleteFile(new String(fileName.getBytes("UTF-8"),"ISO-8859-1"));
                    out.flush();
                    out.close();
                    if(flag){
                        log.info("下载成功");
                    }else{
                        log.error("下载失败");
                    }
                }
            }

        } catch (Exception e) {
            log.error("下载失败");
        }

        return flag;
    }

    /**
     * FTP文件上传工具类
     * @param ftp ftp连接
     * @param filePath 本地路径
     * @param ftpPath ftp路径
     * @return boolean
     */
    public static boolean uploadFile(FTPClient ftp,String filePath,String ftpPath){
        boolean flag = false;
        InputStream in = null;
        try {
            // 设置PassiveMode传输
            ftp.enterLocalPassiveMode();
            //设置二进制传输,使用BINARY_FILE_TYPE,ASC容易造成文件损坏
            ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
            //判断FPT目标文件夹时候存在不存在则创建
            if(!ftp.changeWorkingDirectory(ftpPath)){
                ftp.makeDirectory(ftpPath);
            }
            //跳转目标目录
            ftp.changeWorkingDirectory(ftpPath);

            //上传文件
            File file = new File(filePath);
            in = new FileInputStream(file);
            String tempName = ftpPath+File.separator+file.getName();
            flag = ftp.storeFile(new String (tempName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1),in);
            if(flag){
                log.info("上传成功");
            }else{
                log.error("上传失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("上传失败");
        }finally{
            try {
                if(in != null){
                    in.close();
                }
            } catch (IOException e) {
                //
                e.printStackTrace();
            }
        }
        return flag;
    }

    /**
     * FPT上文件的复制
     * @param ftp  FTPClient对象
     * @param olePath 原文件地址
     * @param newPath 新保存地址
     * @param fileName 文件名
     * @return boolean
     */
    public static boolean copyFile(FTPClient ftp, String olePath, String newPath,String fileName) {
        boolean flag = false;

        try {
            // 跳转到文件目录
            ftp.changeWorkingDirectory(olePath);
            //设置连接模式,不设置会获取为空
            ftp.enterLocalPassiveMode();
            // 获取目录下文件集合
            FTPFile[] files = ftp.listFiles();
            ByteArrayInputStream  in = null;
            ByteArrayOutputStream out = null;
            for (FTPFile file : files) {
                // 取得指定文件并下载
                if (file.getName().equals(fileName)) {

                    //读取文件,使用下载文件的方法把文件写入内存,绑定到out流上
                    out = new ByteArrayOutputStream();
                    ftp.retrieveFile(new String(file.getName().getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1), out);
                    in = new ByteArrayInputStream(out.toByteArray());
                    //创建新目录
                    ftp.makeDirectory(newPath);
                    //文件复制,先读,再写
                    //二进制
                    ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
                    flag = ftp.storeFile(newPath+File.separator+(new String(file.getName().getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1)),in);
                    out.flush();
                    out.close();
                    in.close();
                    if(flag){
                        log.info("转存成功");
                    }else{
                        log.error("复制失败");
                    }


                }
            }
        } catch (Exception e) {
            log.error("复制失败");
        }
        return flag;
    }

    /**
     * 实现文件的移动,这里做的是一个文件夹下的所有内容移动到新的文件,
     * 如果要做指定文件移动,加个判断判断文件名
     * 如果不需要移动,只是需要文件重命名,可以使用ftp.rename(oleName,newName)
     * @param ftp ftp连接
     * @param oldPath 原路径
     * @param newPath 新路径
     * @return boolean
     */
    public static boolean moveFile(FTPClient ftp,String oldPath,String newPath){
        boolean flag = false;

        try {
            ftp.changeWorkingDirectory(oldPath);
            ftp.enterLocalPassiveMode();
            //获取文件数组
            FTPFile[] files = ftp.listFiles();
            //新文件夹不存在则创建
            if(!ftp.changeWorkingDirectory(newPath)){
                ftp.makeDirectory(newPath);
            }
            //回到原有工作目录
            ftp.changeWorkingDirectory(oldPath);
            for (FTPFile file : files) {

                //转存目录
                flag = ftp.rename(new String(file.getName().getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1), newPath+File.separator+new String(file.getName().getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
                if(flag){
                    log.info(file.getName()+"移动成功");
                }else{
                    log.error(file.getName()+"移动失败");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("移动文件失败");
        }
        return flag;
    }

    /**
     * 删除FTP上指定文件夹下文件及其子文件方法,添加了对中文目录的支持
     * @param ftp FTPClient对象
     * @param ftpFolder 需要删除的文件夹
     * @return boolean
     */
    public static boolean deleteByFolder(FTPClient ftp,String ftpFolder){
        boolean flag = false;
        try {
            ftp.changeWorkingDirectory(new String(ftpFolder.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
            ftp.enterLocalPassiveMode();
            FTPFile[] files = ftp.listFiles();
            for (FTPFile file : files) {
                //判断为文件则删除
                if(file.isFile()){
                    ftp.deleteFile(new String(file.getName().getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
                }
                //判断是文件夹
                if(file.isDirectory()){
                    String childPath = ftpFolder + File.separator+file.getName();
                    //递归删除子文件夹
                    deleteByFolder(ftp,childPath);
                }
            }
            //循环完成后删除文件夹
            flag = ftp.removeDirectory(new String(ftpFolder.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
            if(flag){
                log.info(ftpFolder+"文件夹删除成功");
            }else{
                log.error(ftpFolder+"文件夹删除成功");
            }

        } catch (Exception e) {
            e.printStackTrace();
            log.error("删除失败");
        }
        return flag;

    }

    /**
     * 列出目录下的所有目录
     * @param ftp  ftp连接
     * @param folderPath  ftp路径
     * @return 目录列表
     */
    public static List<String> listDirByPath(FTPClient ftp, String folderPath) {
        List<String> dirs = Lists.newArrayList();
        try {
            FTPFile[] ftpDirs = ftp.listFiles(new String(folderPath.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
            if(Objects.nonNull(ftpDirs)){
                for(FTPFile dir : ftpDirs){
                    if(dir.isDirectory()){
                        dirs.add(dir.getName());
                    }
                }
            }
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        return dirs;
    }

    /**
     * 列出目录下的所有文件
     * @param ftp ftp连接
     * @param folderPath ftp路径
     * @return 文件列表
     */
    public static List<String> listFilesByPath(FTPClient ftp, String folderPath) {

        List<String> files = Lists.newArrayList();
        try {
            FTPFile[] ftpFiles = ftp.listFiles(new String(folderPath.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
            if(Objects.nonNull(ftpFiles)){
                for(FTPFile file : ftpFiles){
                    //筛选15兆以下的文件
                    long fileSize = file.getSize() / 1024 / 1024;
                    if(file.isFile() && fileSize <= 15){
                        files.add(file.getName());
                    }
                }
            }
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        return files;
    }




    public static void main(String[] args) throws IOException {

        FTPClient ftpClient = getFtpClient("xxx.xxx.xxx.xxx", 21, "ftpuser", "ftpuser");

        ftpClient.enterLocalPassiveMode();
        FTPFile[] ftpFiles = ftpClient.listFiles("/");


        if(Objects.nonNull(ftpFiles)){
            for(FTPFile s : ftpFiles){
                if(s.isFile()){
                    System.out.println(s.getName());
                }
            }
        }

        FTPFile[] ftpDirs = ftpClient.listDirectories("/");
        if(Objects.nonNull(ftpDirs)) {
            for (FTPFile s : ftpDirs) {
                System.out.println(s.getName());
            }
        }
//        downLoadFTP(ftpClient, "/home/vsftpd/", "ftp_test.xlsx", "C:\\Users\\hz20055212\\Downloads");
        //test.copyFile(ftp, "/file", "/txt/temp", "你好.txt");
        //test.uploadFile(ftp, "C:\\下载\\你好.jpg", "/");
        //test.moveFile(ftp, "/file", "/txt/temp");
        //test.deleteByFolder(ftp, "/txt");
        closeFtp(ftpClient);
        System.exit(0);
    }

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值