java FTP连接上传下载,TLS协议

package com.xhd.edi.ftp.util.ftp;


import lombok.extern.java.Log;
import org.apache.commons.net.ftp.*;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;


@Component
@Log
public class FTPUtils {

    private FTPClient ftpClient = null;
    private final String server = "";
    private final int port = 21;
    private final String userName = "";
    private final String userPassword = "";
    private final String rootFilePath = "";
    private final String saveFilePath = "";


    /**
     * <p>Title: 连接服务器</p>
     * <p>Description: </p>
     *
     * @return 连接成功与否 true:成功, false:失败
     */
    public boolean open() {
        // 判断是否已连接
        if (ftpClient != null && ftpClient.isConnected()) {
            return true;
        }

        try {
            //TLS 用FTPSClient,FTP 用FTPClient
            ftpClient = new FTPSClient();

            // 连接FTP服务器
            ftpClient.connect(this.server, this.port);
            // 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
            ftpClient.login(this.userName, this.userPassword);
            // 检测连接是否成功
            int reply = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                log.info("FTP服务器拒绝连接.");
                this.close();
                System.exit(1);
            }
            log.info("FTP连接成功:" + this.server + ";port:" + this.port + ";name:" + this.userName + ";pwd:" + this.userPassword);
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE); // 设置上传模式.binally or ascii
            ftpClient.setFileTransferMode(ftpClient.BINARY_FILE_TYPE);
            ftpClient.enterLocalPassiveMode();
            return true;
        } catch (Exception e) {
            this.close();
            e.printStackTrace();
            return false;
        }

    }

    /**
     * <p>Title: 切换到父目录</p>
     * <p>Description: </p>
     *
     * @return 切换结果 true:成功, false:失败

     */
    private boolean changeToParentDir() {
        try {
            return ftpClient.changeToParentDirectory();
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * <p>Title: 改变当前目录到指定目录</p>
     * <p>Description: </p>
     *
     * @param dir 目的目录
     * @return 切换结果 true:成功,false:失败
     */
    private boolean cd(String dir) {
        try {
            return ftpClient.changeWorkingDirectory(dir);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * <p>Title: 获取目录下所有的文件名称</p>
     * <p>Description: </p>
     *
     * @param filePath 指定的目录
     * @return 文件列表, 或者null
     */
    private FTPFile[] getFileList(String filePath) {
        try {
            return ftpClient.listFiles(filePath);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * <p>Title: 层层切换工作目录</p>
     * <p>Description: </p>
     *
     * @param ftpPath 目的目录
     * @return 切换结果
     */
    public boolean changeDir(String ftpPath) {
        if (!ftpClient.isConnected()) {
            return false;
        }
        try {
            // 将路径中的斜杠统一
            char[] chars = ftpPath.toCharArray();
            StringBuffer sbStr = new StringBuffer(256);
            for (int i = 0; i < chars.length; i++) {
                if ('\\' == chars[i]) {
                    sbStr.append('/');
                } else {
                    sbStr.append(chars[i]);
                }
            }
            ftpPath = sbStr.toString();
            if (ftpPath.indexOf('/') == -1) {
                // 只有一层目录
                ftpClient.changeWorkingDirectory(new String(ftpPath.getBytes(), "UTF-8"));
            } else {
                // 多层目录循环创建
                String[] paths = ftpPath.split("/");
                for (int i = 0; i < paths.length; i++) {
                    ftpClient.changeWorkingDirectory(new String(paths[i].getBytes(), "UTF-8"));
                }
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * <p>Title: 循环创建目录,并且创建完目录后,设置工作目录为当前创建的目录下</p>
     * <p>Description: </p>
     *
     * @param ftpPath 需要创建的目录
     * @return
     */
    public boolean mkDir(String ftpPath) {
        if (!ftpClient.isConnected()) {
            return false;
        }
        try {
            // 将路径中的斜杠统一
            char[] chars = ftpPath.toCharArray();
            StringBuffer sbStr = new StringBuffer(256);
            for (int i = 0; i < chars.length; i++) {
                if ('\\' == chars[i]) {
                    sbStr.append('/');
                } else {
                    sbStr.append(chars[i]);
                }
            }
            ftpPath = sbStr.toString();
            log.info("ftpPath:" + ftpPath);
            if (ftpPath.indexOf('/') == -1) {
                // 只有一层目录
                ftpClient.makeDirectory(new String(ftpPath.getBytes(), "UTF-8"));
                ftpClient.changeWorkingDirectory(new String(ftpPath.getBytes(), "UTF-8"));
            } else {
                // 多层目录循环创建
                String[] paths = ftpPath.split("/");
                for (int i = 0; i < paths.length; i++) {
                    ftpClient.makeDirectory(new String(paths[i].getBytes(), "UTF-8"));
                    ftpClient.changeWorkingDirectory(new String(paths[i].getBytes(), "UTF-8"));
                }
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * <p>Title: 上传文件到FTP服务器</p>
     * <p>Description: </p>
     *
     * @param localDirectoryAndFileName 本地文件目录和文件名
     * @param ftpFileName               上传到服务器的文件名()
     * @param ftpDirectory              FTP目录如:/path1/pathb2/,如果目录不存在会自动创建目录(目录可以省略)
     * @return
     */
    public boolean upload(String localDirectoryAndFileName, String ftpFileName, String ftpDirectory) {
        if (!ftpClient.isConnected()) {
            return false;
        }
        boolean flag = false;
        if (ftpClient != null) {
            File srcFile = new File(localDirectoryAndFileName);
            FileInputStream fis = null;
            try {
                fis = new FileInputStream(srcFile);
                // 创建目录
                this.mkDir(ftpDirectory);
                ftpClient.setBufferSize(100000);
                ftpClient.setControlEncoding("UTF-8");
                // 设置文件类型(二进制)
                ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);

                if (ftpFileName == null || ftpFileName == "") {
                    ftpFileName = srcFile.getName();
                }

                // 上传
                flag = ftpClient.storeFile(new String(ftpFileName.getBytes(), "UTF-8"), fis);
            } catch (Exception e) {
                this.close();
                e.printStackTrace();
                return false;
            } finally {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        log.info("上传文件成功,本地文件名: " + localDirectoryAndFileName + ",上传到目录:" + ftpDirectory + "/" + ftpFileName);
        return flag;
    }

    /**
     * <p>Title: 从FTP服务器上下载文件</p>
     * <p>Description: </p>
     *
     * @param ftpDirectoryAndFileName   ftp服务器文件路径,以/dir形式开始
     * @param localDirectoryAndFileName 保存到本地的目录
     * @return
     */
    public boolean get(String ftpDirectoryAndFileName, String localDirectoryAndFileName) {
        if (!ftpClient.isConnected()) {
            return false;
        }
        ftpClient.enterLocalPassiveMode(); // Use passive mode as default
        try {
            // 将路径中的斜杠统一
            char[] chars = ftpDirectoryAndFileName.toCharArray();
            StringBuffer sbStr = new StringBuffer(256);
            for (int i = 0; i < chars.length; i++) {
                if ('\\' == chars[i]) {
                    sbStr.append('/');
                } else {
                    sbStr.append(chars[i]);
                }
            }
            ftpDirectoryAndFileName = sbStr.toString();
            String filePath = ftpDirectoryAndFileName.substring(0, ftpDirectoryAndFileName.lastIndexOf("/"));
            String fileName = ftpDirectoryAndFileName.substring(ftpDirectoryAndFileName.lastIndexOf("/") + 1);
            this.changeDir(filePath);
            ftpClient.retrieveFile(new String(fileName.getBytes(), "UTF-8"), new FileOutputStream(localDirectoryAndFileName)); // download
            // file
            log.info(ftpClient.getReplyString()); // check result
            log.info("从ftp服务器上下载文件:" + ftpDirectoryAndFileName + ", 保存到:" + localDirectoryAndFileName);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * <p>Title: 返回FTP目录下的文件列表</p>
     * <p>Description: </p>
     *
     * @param pathName
     * @return
     */
    public String[] getFileNameList(String pathName) {
        try {
            return ftpClient.listNames(pathName);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * <p>Title: 删除FTP上的文件</p>
     * <p>Description: </p>
     *
     * @param ftpDirAndFileName 路径开头不能加/,比如应该是test/filename1
     * @return
     */
    public boolean deleteFile(String ftpDirAndFileName) {
        if (!ftpClient.isConnected()) {
            return false;
        }
        try {
            return ftpClient.deleteFile(ftpDirAndFileName);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * <p>Title: 删除FTP目录</p>
     * <p>Description: </p>
     *
     * @param ftpDirectory
     * @return
     */
    public boolean deleteDirectory(String ftpDirectory) {
        if (!ftpClient.isConnected()) {
            return false;
        }
        try {
            return ftpClient.removeDirectory(ftpDirectory);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * <p>Title: 关闭链接</p>
     * <p>Description: </p>
     */
    public void close() {
        try {
            if (ftpClient != null && ftpClient.isConnected()) {
                ftpClient.disconnect();
            }
            log.info("成功关闭连接,服务器ip:" + this.server + ", 端口:" + this.port);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        FTPUtils ftp = new FTPUtils();
        boolean flag = ftp.open();
        if (flag) {
            String[] fileNameList = ftp.getFileNameList("");
            // 下载
            ftp.get("", "E:/1.txt");
//            boolean b = ftp.deleteFile("");
//            log.info(b);
            ftp.close();
        }
    }

    @Scheduled(fixedRate = 60 * 60 * 1000)  //每隔60分钟执行一次定时任务
    public void ediTask() {
        log.info("开始定时");
        FTPUtils ftp = new FTPUtils();
        if (ftp.open()) {
            String[] fileNameList = ftp.getFileNameList(rootFilePath);
            if (fileNameList != null && fileNameList.length > 0) {
                for (String fileName : fileNameList) {
                    boolean getOK = ftp.get(rootFilePath + fileName, saveFilePath + fileName);
                    if (getOK) {
                        ftp.deleteFile(rootFilePath + fileName);
                    }
                }
            }
            ftp.close();
        }
    }
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值