JAVA的FTP和SFTP相关操作工具类

一、FTP

文件传输协议(File Transfer Protocol,FTP)是用于在网络上进行文件传输的一套标准协议,它工作在 OSI 模型的第七层, TCP 模型的第四层, 即应用层, 使用 TCP 传输而不是 UDP, 客户在和服务器建立连接前要经过一个“三次握手”的过程, 保证客户与服务器之间的连接是可靠的, 而且是面向连接, 为数据传输提供可靠保证。

FTP允许用户以文件操作的方式(如文件的增、删、改、查、传送等)与另一主机相互通信。然而, 用户并不真正登录到自己想要存取的计算机上面而成为完全用户, 可用FTP程序访问远程资源, 实现用户往返传输文件、目录管理以及访问电子邮件等等, 即使双方计算机可能配有不同的操作系统和文件存储方式。

1.1 引入maven依赖

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

1.2 FtpUtil工具类

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.commons.net.ftp.FTPSClient;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;

/**
 * @Author: huangyibo
 * @Date: 2023/5/15 15:39
 * @Description:
 */

@Slf4j
public class FtpUtil {

    /**
     * 获取FTPClient对象
     * @param ftpHost       FTP主机服务器
     * @param ftpPassword   FTP 登录密码
     * @param ftpUserName   FTP登录用户名
     * @param ftpPort       FTP端口 默认为21
     * @return
     */
    public static FTPClient getFTPClient(String ftpHost, String ftpUserName, String ftpPassword, int ftpPort, boolean ssl) {
        FTPClient ftpClient = new FTPClient();
        try {
            ftpClient = ssl ? new FTPSClient("TLS", true) : new FTPClient();
            // 中文支持
            ftpClient.setControlEncoding("UTF-8");
            // 连接FTP服务器
            ftpClient.connect(ftpHost, ftpPort);
            // 登陆FTP服务器
            ftpClient.login(ftpUserName, ftpPassword);
            if (ssl) {
                ((FTPSClient) ftpClient).execPBSZ(0);
                ((FTPSClient) ftpClient).execPROT("P");
            }
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftpClient.enterLocalPassiveMode();
            if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                log.info("未连接到FTP,用户名或密码错误。");
                ftpClient.disconnect();
            } else {
                log.info("FTP连接成功。");
            }
        } catch (SocketException e) {
            e.printStackTrace();
            log.info("FTP的IP地址可能错误,请正确配置。");
        } catch (IOException e) {
            e.printStackTrace();
            log.info("FTP的端口错误,请正确配置。");
        }
        return ftpClient;
    }

    /**
     * 从FTP服务器下载文件
     * @param ftpHost             FTP IP地址
     * @param ftpUserName         FTP 用户名
     * @param ftpPassword         FTP用户名密码
     * @param ftpPort             FTP端口
     * @param ftpPath             FTP服务器中文件所在路径 格式: ftptest/aa
     * @param localPath           下载到本地的位置 格式:H:/download
     * @param fileName            FTP服务器上要下载的文件名称
     * @param targetFileName      下载到本地的文件名称
     */
    public static void downloadFtpFile(String ftpHost, String ftpUserName, String ftpPassword, int ftpPort, String ftpPath, String localPath, String fileName, String targetFileName, boolean ssl) {

        FTPClient ftpClient = null;
        try {
            ftpClient = getFTPClient(ftpHost, ftpUserName, ftpPassword, ftpPort, ssl);
            ftpClient.changeWorkingDirectory(ftpPath);
            System.out.println("连接成功,改变目录中...");
            ftpClient.makeDirectory("summer");

            //编码文件格式,解决中文文件名
            String f_ame = new String(fileName.getBytes("GBK"), FTP.DEFAULT_CONTROL_ENCODING);

            File localFile = new File(localPath + File.separatorChar + targetFileName);
            OutputStream os = new FileOutputStream(localFile);
            ftpClient.retrieveFile(f_ame, os);
            os.close();
            ftpClient.logout();

        } catch (FileNotFoundException e) {
            log.error("没有找到" + ftpPath + "文件");
            e.printStackTrace();
        } catch (SocketException e) {
            log.error("连接FTP失败.");
            e.printStackTrace();
        } catch (IOException e) {
            log.error("文件读取错误。");
            e.printStackTrace();
        }
    }

    /**
     * Description:             向FTP服务器上传文件
     * @param ftpHost              FTP服务器hostname
     * @param ftpPort              FTP服务器端口
     * @param ftpUserName          FTP登录账号
     * @param ftpPassword          FTP登录密码
     * @param ftpPath          FTP服务器文件存放路径。例如分日期存放:/2015/01/01。文件的路径为basePath+filePath
     * @param filename          上传到FTP服务器上的文件名
     * @param input             输入流
     * @return                  成功返回true,否则返回false
     */
    public static boolean uploadFile(String ftpHost, String ftpUserName, String ftpPassword, int ftpPort, String ftpPath, String filename, InputStream input, boolean ssl) {
        boolean result = false;
        FTPClient ftpClient = new FTPClient();
        try {
            int reply;
            ftpClient = getFTPClient(ftpHost, ftpUserName, ftpPassword, ftpPort, ssl);
            ftpClient.changeWorkingDirectory(ftpPath);

            reply = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.disconnect();
                return result;
            }
            //编码文件名,支持中文文件名
            filename = new String(filename.getBytes("GBK"), FTP.DEFAULT_CONTROL_ENCODING);
            //上传文件
            if (!ftpClient.storeFile(filename, input)) {
                return result;
            }
            input.close();
            ftpClient.logout();
            result = true;
        } catch (IOException e) {
            log.error("文件上传错误", e);
            e.printStackTrace();
        } finally {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException ioe) {
                    log.error("ftpClient关闭错误", ioe);
                }
            }
        }
        return result;
    }
}

1.3 FtpUtils工具类

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
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.nio.file.Files;
import java.nio.file.StandardCopyOption;

/**
 * @Author: huangyibo
 * @Date: 2023/5/15 15:32
 * @Description:
 */

@Component
public class FtpUtils {

    @Value("${ftp.username}")
    private String fUsername;

    private  static String FTP_USER;

    @Value("${ftp.password}")
    private String fPassword;

    private  static String FTP_PASSWORD;

    @Value("${ftp.host}")
    private String fHost;

    private  static String FTP_IP;

    @Value("${ftp.port}")
    private Integer fPort;

    private  static Integer FTP_PORT;

    @Value("${ftp.charset.iso}")
    private String fCharsetIso;

    private  static String CHARSET_ISO;

    @PostConstruct
    public void init(){
        FTP_USER=fUsername;
        FTP_PASSWORD=fPassword;
        FTP_IP=fHost;
        FTP_PORT=fPort;
        CHARSET_ISO=fCharsetIso;
    }

    /**
     * 下载指定Ftp文件夹的全部文件
     * @param folderPath ftp文件夹路径
     * @param localPath 下载本地磁盘路径
     * @return
     */
    public static Boolean downLoadFolder(String folderPath,String localPath){
        FTPClient ftp = getFTPClient();
        try {
            if(ftp == null){
                return false;
            }
            ftp.enterLocalPassiveMode();
            //切换到文件目录
            ftp.changeWorkingDirectory(folderPath);
            //获取文件集合
            FTPFile[] files = ftp.listFiles();
            for(FTPFile file : files){
                if(file.isFile()){
                    try (OutputStream out = new FileOutputStream(localPath +  "\\\\" + file.getName())){
                        ftp.retrieveFile(new String(file.getName().getBytes(),CHARSET_ISO),out);
                        out.flush();
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }finally {
            closeFtp(ftp);
        }
        return true;
    }

    /**
     * 文件下载
     * @param parentPath 文件在ftp上级路径
     * @param ftpFileName 文件在ftp名称
     * @param localPath 下载本地磁盘路径
     * @return
     */
    public static Boolean downLoad(String parentPath,String ftpFileName,String localPath){
        FTPClient ftp = getFTPClient();
        try {
            if(ftp == null){
                return false;
            }
            ftp.enterLocalPassiveMode();
            parentPath = parentPath + "/" +ftpFileName;
            System.out.println(parentPath);
            //根据文件名称获取输入流
            try (InputStream in = ftp.retrieveFileStream(new String(parentPath.getBytes(),CHARSET_ISO))){
                //写入本地文件目录
                File dest = new File(localPath, ftpFileName);
                if (!dest.getParentFile().exists()) {
                    System.out.println("创建文件夹.................");
                    dest.getParentFile().mkdirs();
                }
                Files.copy(in, dest.toPath(), StandardCopyOption.REPLACE_EXISTING);
                return true;
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            closeFtp(ftp);
        }
        return false;
    }

    /**
     * 文件上传
     * @param filePath 文件路径
     * @param ftpPath ftp路径
     * @return
     */
    public static Boolean upload(String filePath,String ftpPath){
        return upload(new File(filePath),ftpPath);
    }

    /**
     * 文件上传
     * @param file 文件对象
     * @param ftpPath ftp路径
     * @return
     */
    public static Boolean upload(File file,String ftpPath){
        FTPClient ftp = getFTPClient();
        try {
            if(ftp == null){
                return false;
            }
            //设置被动模式
            ftp.enterLocalPassiveMode();
            //二进制传输
            ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
            //如果ftp目录不存在则创建目录
            if(!ftp.changeWorkingDirectory(ftpPath)){
                ftp.makeDirectory(ftpPath);
                //改变工作目录
                ftp.changeWorkingDirectory(ftpPath);
            }
            //文件名
            String fileName = file.getName();
            //上传文件
            if(ftp.storeFile(new String(fileName.getBytes(),CHARSET_ISO),new FileInputStream(file))){
                return true;
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            closeFtp(ftp);
        }
        return false;
    }

    /**
     * 获取Ftp客户端对象
     * @return
     */
    private static FTPClient getFTPClient(){
        try {
            FTPClient ftpClient = new FTPClient();
            ftpClient.connect(FTP_IP,FTP_PORT);
            //连接超时时间
            ftpClient.setConnectTimeout(2 * 60 * 1000);
            //传输超时时间
            ftpClient.setDataTimeout(2 * 60 * 1000);
            ftpClient.setControlEncoding("utf-8");
            //用户名密码登录
            ftpClient.login(FTP_USER,FTP_PASSWORD);
            //校验响应码
            if(!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())){
                ftpClient.disconnect();
                return null;
            }
            return ftpClient;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 关闭Ftp客户端
     * @param ftp
     */
    private static void closeFtp(FTPClient ftp){
        try {
            if(ftp != null){
                ftp.logout();
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                if(ftp != null){
                    ftp.disconnect();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

二、SFTP

摘自百度百科:SSH文件传输协议,是一种数据流链接,提供文件访问、传输和管理功能的网络传输协议。

SFTP允许用户以文件操作的方式(如文件的增、删、改、查、传送等)与另一主机相互通信。

2.1 引入maven依赖

<dependency>
    <groupId>com.jcraft</groupId>
    <artifactId>jsch</artifactId>
    <version>0.1.55</version>
</dependency>

2.2 SftpUtil

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;

/**
 * @Author: huangyibo
 * @Date: 2023/5/15 15:55
 * @Description:
 * sftp工具类,包含以下功能:
 * 获取sftp链接
 * 关闭sftp链接
 * 下载文件
 * 上传文件
 * 删除文件
 * 查找文件
 * 更多功能自行拓展
 */

public class SftpUtil {

    /**
     * 获取一个sftp链接
     * @param host sftp服务器ip
     * @param port 端口
     * @param username 用户名
     * @param password 密码
     * @return 返回ChannelSftp
     * @throws Exception 获取通道时的异常
     */
    public static ChannelSftp getSftpChannel(String host, Integer port, String username, String password) throws Exception{
        Session session;
        Channel channel = null;
        JSch jSch = new JSch();
        try {
            session = jSch.getSession(username, host, port);
            session.setPassword(password);

            // 配置链接的属性
            Properties properties = new Properties();
            properties.setProperty("StrictHostKeyChecking","no");
            session.setConfig(properties);

            // 进行sftp链接
            session.connect();

            // 获取通信通道
            channel = session.openChannel("sftp");
            channel.connect();
        } catch (JSchException e) {
            e.printStackTrace();
            throw e;
        }
        return (ChannelSftp)channel;
    }

    /**
     * 上传文件
     * @param channelSftp sftp通道
     * @param localFile 本地文件
     * @param remoteFile 远程文件
     */
    public static void upload(ChannelSftp channelSftp, String localFile, String remoteFile){
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(localFile);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        try {
            channelSftp.put(inputStream, remoteFile);
        } catch (SftpException e) {
            e.printStackTrace();
        }
    }

    /**
     * 从sftp服务器上下载文件
     * @param channelSftp sftp通道
     * @param remoteFile 远程文件
     * @param localFile 本地文件
     */
    public static void download(ChannelSftp channelSftp, String remoteFile, String localFile){
        OutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(localFile);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        try {
            channelSftp.get(remoteFile, outputStream);
        } catch (SftpException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除文件
     * @param channelSftp sftp通道
     * @param remoteFile 远程文件
     */
    public static void deleteFile(ChannelSftp channelSftp, String remoteFile) throws Exception{
        try {
            channelSftp.rm(remoteFile);
        } catch (SftpException e) {
            e.printStackTrace();
            throw e;
        }
    }

    /**
     * 关闭sftp链接
     * @param channelSftp sftp通道
     * @throws Exception 关闭session的异常
     */
    public static void closeSession(ChannelSftp channelSftp) throws Exception{
        if(channelSftp == null){
            return;
        }

        Session session = null;
        try {
            session = channelSftp.getSession();
        } catch (JSchException e) {
            e.printStackTrace();
            throw e;
        }finally {
            if(session != null){
                session.disconnect();
            }
        }
    }
}

参考:
https://www.freesion.com/article/7677614564/

http://www.manongjc.com/detail/32-qccudmxubjccvrd.html

https://www.cnblogs.com/haidaogege/p/16349279.html

https://blog.csdn.net/Staba/article/details/129476074

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,271评论 5 466
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,725评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,252评论 0 328
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,634评论 1 270
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,549评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 47,985评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,471评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,128评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,257评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,233评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,235评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,940评论 3 316
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,528评论 3 302
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,623评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,858评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,245评论 2 344
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,790评论 2 339

推荐阅读更多精彩内容