Java实现FTP SSL 上传下载删除

前言

Java学习路线个人总结-博客
❤欢迎点赞👍收藏⭐留言 📝分享给需要的小伙伴

  • 支持SSL连接

  • 发现问题

    ftp.listFiles();如果在本地测试正常到服务器为NULL或0的话,检查防火墙或开启端口白名单当时被坑过!!!

Maven

<dependency>
    <groupId>commons-net</groupId>
    <artifactId>commons-net</artifactId>
    <version>3.1</version>
</dependency>

测试代码

/**
     * @param args
     * @return void
     * @Description //TODO 上传
     * @Date 14:56 2020/11/4
     **/
    public static void main11(String[] args) throws Exception {
        FTPSClient ftpsClient = ftpConnection("xxx", 9021, "xxx", "pwd.1234");
        File file1 = new File("C:\\Users\\D\\Desktop\\测试.zip");
        boolean b = uploadFile(file1, "20201104/", ftpsClient);
        System.out.println(b);

    }

    /**
     * @param args
     * @return void
     * @Description //TODO 下载
     * @Date 14:56 2020/11/4
     **/
    public static void main22(String[] args) throws Exception {
        FTPSClient ftpsClient = ftpConnection("xxx", 9021, "xxx", "pwd.1234");
        FTPFile[] ftpFiles = ftpsClient.listFiles();
        LOGGER.warn(ftpFiles + "");
//        boolean success = downLoad("/20201104/测试.zip", "E:\\测试.zip", ftpsClient);
        boolean b = downLoadDirectory("E:/liao/intputfile/", "", ftpsClient);
        System.out.println(b);
    }


    /**
     * @param args
     * @return void
     * @Description //TODO 删除文件
     * @Date 15:21 2020/11/4
     * @Param
     **/
    public static void main(String[] args) throws IOException {
        FTPSClient ftpsClient = ftpConnection("xxx", 9021, "xxx", "pwd.1234");
        ftpsClient.changeWorkingDirectory("/");
        FTPFile[] ftpFiles = ftpsClient.listFiles();
        //获取下面两个文件夹
        List<String> listStr = new ArrayList<>();
        for (FTPFile ftpFile : ftpFiles) {
            listStr.add("/" + ftpFile.getName());
        }
        //删除
        List<String> strList = new ArrayList<>();
        for (String s : listStr) {
            ftpsClient.changeWorkingDirectory(s);
            FTPFile[] ftpFiles1 = ftpsClient.listFiles();
            for (FTPFile ftpFile : ftpFiles1) {
                strList.add(s + "/" + ftpFile.getName());
            }
        }
        for (String s : strList) {
            LOGGER.warn("删除文件目录:{}", s + "/" + s );
            // 切换FTP目录
            ftpsClient.changeWorkingDirectory(s);
            deleteFile(s, null, ftpsClient);
            //刪除文件夾
            ftpsClient.rmd(s);
        }
        //关闭资源
        closeConnection(ftpsClient);

    }

工具类代码

package com.info.provincial.utils;

import org.apache.commons.net.ftp.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.*;

/**
 * @description: FTPSClientUtil
 */
public class FtpClientUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(FtpClientUtil.class);

    /**
     * 关闭连接,使用完连接之后,一定要关闭连接,否则服务器会抛出 Connection reset by peer的错误
     *
     * @throws IOException
     */
    public static void closeConnection(FTPSClient ftpClient) {
        LOGGER.info("【关闭文件服务器连接】");
        if (ftpClient == null) {
            return;
        }
        try {
            ftpClient.disconnect();
        } catch (IOException e) {
            LOGGER.error("【关闭连接失败】", e);
            throw new RuntimeException("关闭连接失败");
        }
    }

    /**
     * 切换工作目录
     *
     * @param directory 目标工作目录
     * @param ftpClient
     * @throws IOException
     */
    public static void changeWorkingDirectory(String directory, FTPSClient ftpClient) {
        LOGGER.info("【切换工作目录】directory : " + directory);
        // 切换到目标工作目录
        try {
            if (!ftpClient.changeWorkingDirectory(directory)) {
                ftpClient.makeDirectory(directory);
                ftpClient.changeWorkingDirectory(directory);
            }
        } catch (IOException e) {
            LOGGER.error("【切换工作目录失败】", e);
            throw new RuntimeException("切换工作目录失败");
        }
    }

    /**
     * @param host     IP地址
     * @param port     端口
     * @param userName 用户名称
     * @param passWord 用户密码
     * @return org.apache.commons.net.ftp.FTPSClient
     * @Description //TODO 连接
     * @Date 15:16 2020/11/4
     * @Param
     **/
    public static FTPSClient ftpConnection(String host, int port, String userName, String passWord) {
        FTPSClient ftpClient = null;
        try {
            ftpClient = new FTPSClient();
            //设置端口,地址
            ftpClient.connect(host, port);
            //被动连接,如果listFiles方法在服务器上为null,看是否关闭防火墙或设置端口为白名单
            ftpClient.enterLocalPassiveMode();
            //设置账号密码
            ftpClient.login(userName, passWord);
            ftpClient.execPBSZ(0);
            ftpClient.execPROT("P");
            //设置二进制文件
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            //设置连接超时时间为60s
            ftpClient.setConnectTimeout(60000);
            //设置数据超时时间为60s
            ftpClient.setDataTimeout(60000);
            ftpClient.setBufferSize(1024);
            ftpClient.setControlEncoding("UTF-8");
            LOGGER.info("FTPSERVICE.ftpConnection  ftpconnection success");
        } catch (Exception e) {
            LOGGER.error("FTPSERVICE.ftpConnection  ftpconnection EXception:", e);
        }
        return ftpClient;
    }

    /***
     * @下载文件夹
     * @param localDirectoryPath 本地地址
     * @param remoteDirectory    远程文件夹
     * */
    public static boolean downLoadDirectory(String localDirectoryPath,
                                            String remoteDirectory, FTPSClient ftp) {
        try {
            String fileName = new File(remoteDirectory).getName();
            localDirectoryPath = localDirectoryPath + fileName + "//";
            new File(localDirectoryPath).mkdirs();

            //切换工作目录
            ftp.changeWorkingDirectory(remoteDirectory);
            FTPFile[] allFile = ftp.listFiles(remoteDirectory);
            LOGGER.warn("当前目录大小:{}", allFile.length);

            if (allFile == null || allFile.length == 0) {
                LOGGER.error("当前:{} 目录没有文件,或文件夹!", remoteDirectory);
            }
            //不是目录,下载文件
            for (int currentFile = 0; currentFile < allFile.length; currentFile++) {
                if (!allFile[currentFile].isDirectory()) {
                    downloadFile(allFile[currentFile].getName(), "",
                            localDirectoryPath, remoteDirectory, ftp);
                }
            }
            //是目录继续递归
            for (int currentFile = 0; currentFile < allFile.length; currentFile++) {
                if (allFile[currentFile].isDirectory()) {
                    String strremoteDirectoryPath = remoteDirectory + "/"
                            + allFile[currentFile].getName();
                    downLoadDirectory(localDirectoryPath,
                            strremoteDirectoryPath, ftp);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            LOGGER.error("下载文件夹失败", e);
            return false;
        }
        return true;
    }


    /***
     * 下载文件
     *
     * @param remoteFileName
     *            待下载文件名称
     * @param localDires
     *            下载到当地那个路径下
     * @param remoteDownLoadPath
     *            remoteFileName所在的路径
     * */

    public static boolean downloadFile(String remoteFileName, String localFileName, String localDires,
                                       String remoteDownLoadPath, FTPSClient ftp) {
        String strFilePath = localDires + remoteFileName;
        if (localFileName != null && localFileName.length() > 0) {
            strFilePath = localDires + localFileName;
        }
        BufferedOutputStream outStream = null;
        boolean success = false;

        try {
            ftp.changeWorkingDirectory(remoteDownLoadPath);
            FTPFile[] fs = ftp.listFiles();
            for (FTPFile ff : fs) {
                LOGGER.warn(ff.getName());
            }
            outStream = new BufferedOutputStream(new FileOutputStream(
                    strFilePath));
            LOGGER.warn(remoteFileName + "开始下载....");
            success = ftp.retrieveFile(new String(remoteFileName.getBytes("UTF-8"), "iso-8859-1"), outStream);
            if (success == true) {
                LOGGER.warn(remoteFileName + "成功下载到" + strFilePath);
                return success;
            }
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error(remoteFileName + "下载失败", e);
        } finally {
            if (null != outStream) {
                try {
                    outStream.flush();
                    outStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        if (success == false) {
            LOGGER.error(remoteFileName + "下载失败!!!");
        }
        return success;
    }

    /***
     * @上传文件夹
     * @param localDirectory
     *            当地文件夹
     * @param remoteDirectoryPath
     *            Ftp 服务器路径 以目录"/"结束
     * */
    public static boolean uploadDirectory(String localDirectory,
                                          String remoteDirectoryPath, FTPSClient ftp) {
        File src = new File(localDirectory);
        try {
            remoteDirectoryPath = remoteDirectoryPath + src.getName() + "/";
            ftp.makeDirectory(remoteDirectoryPath);//创建目录
        } catch (IOException e) {
            e.printStackTrace();
            LOGGER.error(remoteDirectoryPath + "目录创建失败", e);
        }
        File[] allFile = src.listFiles();
        for (int currentFile = 0; currentFile < allFile.length; currentFile++) {
            if (!allFile[currentFile].isDirectory()) {
                String srcName = allFile[currentFile].getPath().toString();
                uploadFile(new File(srcName), remoteDirectoryPath, ftp);
            }
        }
        for (int currentFile = 0; currentFile < allFile.length; currentFile++) {
            if (allFile[currentFile].isDirectory()) {
                // 递归
                uploadDirectory(allFile[currentFile].getPath().toString(),
                        remoteDirectoryPath, ftp);
            }
        }
        return true;
    }


    /***
     * 上传Ftp文件
     *
     * @param localFile 当地文件
     * @param romotUpLoadePath 上传服务器路径
     *            - 应该以/结束
     * */
    public static boolean uploadFile(File localFile, String romotUpLoadePath, FTPSClient ftp) {
        BufferedInputStream inStream = null;
        boolean success = false;
        try {
            //创建目录
//            ftp.makeDirectory(new String(romotUpLoadePath.getBytes("UTF-8"), "iso-8859-1"));
            ftp.changeWorkingDirectory(romotUpLoadePath);// 改变工作路径
            inStream = new BufferedInputStream(new FileInputStream(localFile));
            LOGGER.info(localFile.getName() + "开始上传.....");
            //注意一定要设置字符
            success = ftp.storeFile(new String(localFile.getName().getBytes("UTF-8"), "iso-8859-1"), inStream);
            if (success == true) {
                LOGGER.info(localFile.getName() + "上传成功");
                return success;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            LOGGER.error(localFile + "未找到,上传失败", e);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inStream != null) {
                try {
                    inStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return success;
    }


    /**
     * * 删除文件 *
     *
     * @param pathname FTP服务器保存目录 *
     * @param filename 要删除的文件名称 *
     * @return
     */
    public static boolean deleteFile(String pathname, String filename, FTPClient ftpClient) {
        boolean flag = false;
        try {
            LOGGER.warn("开始删除文件");
            FTPFile[] ftpFiles = ftpClient.listFiles();
            for (FTPFile ftpFile : ftpFiles) {
                //删除文件
                flag = ftpClient.deleteFile(new String(ftpFile.getName().getBytes("UTF-8"), "iso-8859-1"));
            }
            if (flag) {
                LOGGER.warn("删除文件成功");
            }
        } catch (Exception e) {
            LOGGER.error("删除文件失败", e);
            e.printStackTrace();
        }
        return flag;
    }
}    
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

冒险的梦想家

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

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

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

打赏作者

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

抵扣说明:

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

余额充值