JAVA连接FTP工具类

JAVA连接FTP工具类

FTP的MAVEN依赖

<dependency>
    <groupId>commons-net</groupId>
    <artifactId>commons-net</artifactId>
    <version>3.3</version>
    <scope>compile</scope>
</dependency>

FTP工具类

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPFileFilter;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;
import java.io.*;
import java.net.ConnectException;
import java.net.MalformedURLException;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Enumeration;
import java.util.List;


/**
 * @author: 
 * @version: v1.0
 * @description:
 * @date: 2023-01-06
 **/
public class FTPUtils {

    private static Logger log = Logger.getLogger(FTPUtils.class);


    /**
     * 获取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");
            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;
    }




    /**
     * @description: 读取FTP文件
     * @param ftp
     * @param folderPath
     * @param filePath
     * @return {@link boolean}
     **/
    public boolean readFileByFolder(FTPClient ftp,String folderPath,String filePath){
        boolean flage = false;
        try {
            ftp.changeWorkingDirectory(new String(folderPath.getBytes("UTF-8"),"ISO-8859-1"));
            //设置FTP连接模式
            ftp.enterLocalPassiveMode();
            //获取指定目录下文件文件对象集合
            FTPFile files[] = ftp.listFiles();
            InputStream in = null;
            BufferedReader reader = null;
            BufferedWriter bw = null;
            for (FTPFile file : files) {
                //判断为txt文件则解析
                if(file.isFile()){
                    String fileName = file.getName();
                    if(fileName.endsWith(".txt")){
                        in = ftp.retrieveFileStream(new String(file.getName().getBytes("UTF-8"),"ISO-8859-1"));
                        reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
                        String line;
                        bw = new BufferedWriter(new FileWriter(filePath));
                        while((line = reader.readLine())!=null){
                            bw.write(line);
                            bw.newLine();
                        }
                        if(reader!=null){
                            reader.close();
                        }
                        if(in!=null){
                            in.close();
                        }
                        if(bw!=null){
                            bw.flush();
                            bw.close();
                        }
                        //ftp.retrieveFileStream使用了流,需要释放一下,不然会返回空指针
                        ftp.completePendingCommand();
                    }
                }
                //判断为文件夹,递归
                if(file.isDirectory()){
                    String path = folderPath+File.separator+file.getName();
                    readFileByFolder(ftp,path,filePath);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            log.error("文件解析失败");
        }

        return flage;

    }



    /**
     * @description: 下载FTP文件
     * @param ftp
     * @param filePath
     * @param fileName
     * @param downPath
     * @return {@link 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("UTF-8"), "ISO-8859-1"), out);
                    // 下载成功删除文件,看项目需求
                    //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
     * @description:
     * @param ftp
     * @param filePath
     * @param ftpPath
     * @return {@link 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("UTF-8"), "ISO-8859-1"), in);
            if (flag) {
                log.info("上传成功");
            } else {
                log.error("上传失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("上传失败");
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return flag;
    }

 

    /**
     * @description: 复制FTP文件
     * @param ftp
     * @param olePath
     * @param newPath
     * @param fileName
     * @return {@link 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("UTF-8"), "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("UTF-8"), "ISO-8859-1")), in);
                    out.flush();
                    out.close();
                    in.close();
                    if (flag) {
                        log.info("转存成功");
                    } else {
                        log.error("复制失败");
                    }


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


    /**
     * @description: 获取某段时间后的FTP文件
     * @param ftpClient
     * @param workingDir
     * @param dateTime
     * @return {@link FTPFile[]}
     **/
    public static FTPFile[] listFile(FTPClient ftpClient, String workingDir, String dateTime) {

        FTPFile[] ftpFiles = null;
        final long monitoringTime = DateFormatUtils.parseDateFormat2(dateTime).getTime();
        //final long currentTime = new Date().getTime();
        try {
            ftpClient.changeWorkingDirectory(workingDir);
            ftpFiles = ftpClient.listFiles("./", new FTPFileFilter() {
                @Override
                public boolean accept(FTPFile ftpFile) {
                    Calendar timestamp = ftpFile.getTimestamp();
                    long timeInMillis = timestamp.getTimeInMillis();
                    log.info("文件产生的日期为:" + DateFormatUtils.fileNameByTime(timeInMillis));
                    return timeInMillis >= monitoringTime;
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ftpFiles;
    }


    /**
     * @description: 获取FTP某段时间内的文件
     * @param ftpClient
     * @param workingDir
     * @param startTime
     * @param endTime
     * @return {@link FTPFile[]}
     **/
    public static FTPFile[] listFileBetWeenTime(FTPClient ftpClient, String workingDir, String startTime, String endTime) {

        FTPFile[] ftpFiles = null;
        final long monitoringStartTime = DateFormatUtils.parseDateFormat2(startTime).getTime();
        final long monitoringEndTime = DateFormatUtils.parseDateFormat2(endTime).getTime();
        //final long currentTime = new Date().getTime();
        try {
            ftpClient.changeWorkingDirectory(workingDir);
            ftpFiles = ftpClient.listFiles("./", new FTPFileFilter() {
                @Override
                public boolean accept(FTPFile ftpFile) {
                    Calendar timestamp = ftpFile.getTimestamp();
                    long timeInMillis = timestamp.getTimeInMillis();
                    return (timeInMillis >= monitoringStartTime && timeInMillis <= monitoringEndTime);
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ftpFiles;
    }


    /**
     * @description: 获取FTP所有文件
     * @param ftpClient
     * @param workingDir
     * @param ftpFiles
     * @return {@link List<FTPFile>}
     **/
    public static List<FTPFile> listAllFile(FTPClient ftpClient, String workingDir, List<FTPFile> ftpFiles) {

        try {
            ftpClient.changeWorkingDirectory(workingDir);
            FTPFile[] ftpFilesTmp = ftpClient.listFiles();
            for (FTPFile ftpFile : ftpFilesTmp) {
                if (ftpFile.isDirectory()) {
                    listAllFile(ftpClient, workingDir + "/" + ftpFile.getName(), ftpFiles);
                } else {
                    ftpFiles.add(ftpFile);
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return ftpFiles;
    }


    /**
     * @description: 移动FTP文件
     * @param ftp
     * @param oldPath
     * @param newPath
     * @return {@link 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("UTF-8"), "ISO-8859-1"), newPath + File.separator + new String(file.getName().getBytes("UTF-8"), "ISO-8859-1"));
                if (flag) {
                    log.info(file.getName() + "移动成功");
                } else {
                    log.error(file.getName() + "移动失败");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("移动文件失败");
        }
        return flag;
    }


    /**
     * @description: 删除FTP文件夹
     * @param ftp
     * @param ftpFolder
     * @return {@link boolean}
     **/
    public static boolean deleteByFolder(FTPClient ftp, String ftpFolder) {
        boolean flag = false;
        try {
            ftp.changeWorkingDirectory(new String(ftpFolder.getBytes("UTF-8"), "ISO-8859-1"));
            ftp.enterLocalPassiveMode();
            FTPFile[] files = ftp.listFiles();
            for (FTPFile file : files) {
                //判断为文件则删除
                if (file.isFile()) {
                    ftp.deleteFile(new String(file.getName().getBytes("UTF-8"), "ISO-8859-1"));
                }
                //判断是文件夹
                if (file.isDirectory()) {
                    String childPath = FtpFolder + File.separator + file.getName();
                    //递归删除子文件夹
                    deleteByFolder(ftp, childPath);
                }
            }
            //循环完成后删除文件夹
            flag = ftp.removeDirectory(new String(FtpFolder.getBytes("UTF-8"), "ISO-8859-1"));
            if (flag) {
                log.info(FtpFolder + "文件夹删除成功");
            } else {
                log.error(FtpFolder + "文件夹删除成功");
            }

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

    }


    /**
     * * 删除文件 *
     *
     * @param workDir FTP服务器保存目录 *
     * @param filename 要删除的文件名称 *
     * @return
     */
    public static boolean deleteFile(FTPClient client, String workDir, String filename) {
        boolean flag = false;
        try {
            System.out.println("开始删除文件");
            // 切换FTP目录
            client.changeWorkingDirectory(workDir);
            client.dele(filename);
            flag = true;
            System.out.println("删除文件成功");
        } catch (Exception e) {
            System.out.println("删除文件失败");
            e.printStackTrace();
        }
        return flag;
    }


    /**
     * 关闭FTP方法
     *
     * @param ftp
     * @return
     */
    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;
    }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值