SpringBoot项目集成FTP的方法步骤

 更新时间:2021年10月28日 11:07:55   作者:Ijiran  
本文主要介绍了SpringBoot项目集成FTP的方法步骤,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

写在前面

FTP是一个文件传输协议,被开发人员广泛用于在互联网中文件传输的一套标准协议。
而我们通常在开发过程中也要通过FTP来搭建文件系统,用于存储系统文件等。
目前正值SpringBoot热潮,所以我们接下来会一起学习一下SpringBoot如何集成FTP,以及相关的FTP组件包,还有其主要提供的几个方法。

当然在这系列文章结尾,我们还会给出确切的FTP操作工具类,算是一些小成果,希望和大家共勉。

FTP相关软件安装

我在此就不介绍如何安装FTP了,但是我可以推荐给大家一些软件作为选择。
Linux版本,推荐使用vsftpd进行搭建FTP,只需要改指定的几个配置,添加上用户即可。
Windows版本,推荐使用Serv-U进行搭建FTP,图形化界面,有中文版,操作起来很简单。

开始集成

引入相关jar包

这里我们对FTP相关的组件包使用的是edtFTPj,其实之前很多人都选择的是Java自带的包来实现FTP功能的。
在我们的SpringBoot项目中pom.xml下添加以下依赖。

<dependency>
    <groupId>com.enterprisedt</groupId>
    <artifactId>edtFTPj</artifactId>
    <version>1.5.3</version>
</dependency>

更新maven进行引入,然后我们进行下一步。

引入FTPUtils.java和FTPHelper.java

引入两个工具类。

我这里先贡献一下代码,请大家酌情作为参考。

/**
 * Ftp 工具类
 */
public class FtpHelper {

    private FTPClient ftp;

    public FtpHelper() {

    }

    /**
     * 初始化Ftp信息
     *
     * @param ftpServer   ftp服务器地址
     * @param ftpPort     Ftp端口号
     * @param ftpUsername ftp 用户名
     * @param ftpPassword ftp 密码
     */
    public FtpHelper(String ftpServer, int ftpPort, String ftpUsername,
                     String ftpPassword) {
        connect(ftpServer, ftpPort, ftpUsername, ftpPassword);
    }

    /**
     * 连接到ftp
     *
     * @param ftpServer   ftp服务器地址
     * @param ftpPort     Ftp端口号
     * @param ftpUsername ftp 用户名
     * @param ftpPassword ftp 密码
     */
    public void connect(String ftpServer, int ftpPort, String ftpUsername, String ftpPassword) {
        ftp = new FTPClient();
        try {
            ftp.setControlEncoding("UTF-8");
            ftp.setRemoteHost(ftpServer);
            ftp.setRemotePort(ftpPort);
            ftp.setTimeout(6000);
            ftp.setConnectMode(FTPConnectMode.ACTIVE);
            ftp.connect();
            ftp.login(ftpUsername, ftpPassword);
            ftp.setType(FTPTransferType.BINARY);
        } catch (Exception e) {
            e.printStackTrace();
            ftp = null;
        }
    }

    /**
     * 更改ftp路径
     *
     * @param ftp
     * @param dirName
     * @return
     */
    public boolean checkDirectory(FTPClient ftp, String dirName) {
        boolean flag;
        try {
            ftp.chdir(dirName);
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
        }
        return flag;
    }

    /**
     * 断开ftp链接
     */
    public void disconnect() {
        try {
            if (ftp.connected()) {
                ftp.quit();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 读取ftp文件流
     *
     * @param filePath ftp文件路径
     * @return s
     * @throws Exception
     */
    public InputStream downloadFile(String filePath) throws Exception {
        InputStream inputStream = null;
        String fileName = "";
        filePath = StringUtils.removeStart(filePath, "/");
        int len = filePath.lastIndexOf("/");
        if (len == -1) {
            if (filePath.length() > 0) {
                fileName = filePath;
            } else {
                throw new Exception("没有输入文件路径");
            }
        } else {
            fileName = filePath.substring(len + 1);

            String type = filePath.substring(0, len);
            String[] typeArray = type.split("/");
            for (String s : typeArray) {
                ftp.chdir(s);
            }
        }
        byte[] data;
        try {
            data = ftp.get(fileName);
            inputStream = new ByteArrayInputStream(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return inputStream;
    }

    /**
     * 上传文件到ftp
     *
     * @param file     文件对象
     * @param filePath 上传的路径
     * @throws Exception
     */
    public void uploadFile(File file, String filePath) throws Exception {
        InputStream inStream = new FileInputStream(file);
        uploadFile(inStream, filePath);
    }

    /**
     * 上传文件到ftp
     *
     * @param inStream 上传的文件流
     * @param filePath 上传路径
     * @throws Exception
     */
    public void uploadFile(InputStream inStream, String filePath)
            throws Exception {
        if (inStream == null) {
            return;
        }
        String fileName = "";
        filePath = StringUtils.removeStart(filePath, "/");
        int len = filePath.lastIndexOf("/");
        if (len == -1) {
            if (filePath.length() > 0) {
                fileName = filePath;
            } else {
                throw new Exception("没有输入文件路径");
            }
        } else {
            fileName = filePath.substring(len + 1);
            String type = filePath.substring(0, len);
            String[] typeArray = type.split("/");
            for (String s : typeArray) {
                if (!checkDirectory(ftp, s)) {
                    ftp.mkdir(s);
                }
            }
        }
        ftp.put(inStream, fileName);
    }

    /**
     * 删除ftp文件
     *
     * @param filePath 文件路径
     * @throws Exception
     */
    public void deleteFile(String filePath) throws Exception {
        String fileName = "";
        filePath = StringUtils.removeStart(filePath, "/");
        int len = filePath.lastIndexOf("/");
        if (len == -1) {
            if (filePath.length() > 0) {
                fileName = filePath;
            } else {
                throw new Exception("没有输入文件路径");
            }
        } else {
            fileName = filePath.substring(len + 1);

            String type = filePath.substring(0, len);
            String[] typeArray = type.split("/");
            for (String s : typeArray) {
                if (checkDirectory(ftp, s)) {
                    ftp.chdir(s);
                }
            }
        }
        ftp.delete(fileName);
    }

    /**
     * 切换目录
     *
     * @param path
     * @throws Exception
     */
    public void changeDirectory(String path) {
        if (!ValidateUtils.isEmpty(path)) {
            try {
                ftp.chdir(path);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
/**
 * Ftp 工具类
 */
public class FtpHelper {

    private FTPClient ftp;

    public FtpHelper() {

    }

    /**
     * 初始化Ftp信息
     *
     * @param ftpServer   ftp服务器地址
     * @param ftpPort     Ftp端口号
     * @param ftpUsername ftp 用户名
     * @param ftpPassword ftp 密码
     */
    public FtpHelper(String ftpServer, int ftpPort, String ftpUsername,
                     String ftpPassword) {
        connect(ftpServer, ftpPort, ftpUsername, ftpPassword);
    }

    /**
     * 连接到ftp
     *
     * @param ftpServer   ftp服务器地址
     * @param ftpPort     Ftp端口号
     * @param ftpUsername ftp 用户名
     * @param ftpPassword ftp 密码
     */
    public void connect(String ftpServer, int ftpPort, String ftpUsername, String ftpPassword) {
        ftp = new FTPClient();
        try {
            ftp.setControlEncoding("UTF-8");
            ftp.setRemoteHost(ftpServer);
            ftp.setRemotePort(ftpPort);
            ftp.setTimeout(6000);
            ftp.setConnectMode(FTPConnectMode.ACTIVE);
            ftp.connect();
            ftp.login(ftpUsername, ftpPassword);
            ftp.setType(FTPTransferType.BINARY);
        } catch (Exception e) {
            e.printStackTrace();
            ftp = null;
        }
    }

    /**
     * 更改ftp路径
     *
     * @param ftp
     * @param dirName
     * @return
     */
    public boolean checkDirectory(FTPClient ftp, String dirName) {
        boolean flag;
        try {
            ftp.chdir(dirName);
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
        }
        return flag;
    }

    /**
     * 断开ftp链接
     */
    public void disconnect() {
        try {
            if (ftp.connected()) {
                ftp.quit();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 读取ftp文件流
     *
     * @param filePath ftp文件路径
     * @return s
     * @throws Exception
     */
    public InputStream downloadFile(String filePath) throws Exception {
        InputStream inputStream = null;
        String fileName = "";
        filePath = StringUtils.removeStart(filePath, "/");
        int len = filePath.lastIndexOf("/");
        if (len == -1) {
            if (filePath.length() > 0) {
                fileName = filePath;
            } else {
                throw new Exception("没有输入文件路径");
            }
        } else {
            fileName = filePath.substring(len + 1);

            String type = filePath.substring(0, len);
            String[] typeArray = type.split("/");
            for (String s : typeArray) {
                ftp.chdir(s);
            }
        }
        byte[] data;
        try {
            data = ftp.get(fileName);
            inputStream = new ByteArrayInputStream(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return inputStream;
    }

    /**
     * 上传文件到ftp
     *
     * @param file     文件对象
     * @param filePath 上传的路径
     * @throws Exception
     */
    public void uploadFile(File file, String filePath) throws Exception {
        InputStream inStream = new FileInputStream(file);
        uploadFile(inStream, filePath);
    }

    /**
     * 上传文件到ftp
     *
     * @param inStream 上传的文件流
     * @param filePath 上传路径
     * @throws Exception
     */
    public void uploadFile(InputStream inStream, String filePath)
            throws Exception {
        if (inStream == null) {
            return;
        }
        String fileName = "";
        filePath = StringUtils.removeStart(filePath, "/");
        int len = filePath.lastIndexOf("/");
        if (len == -1) {
            if (filePath.length() > 0) {
                fileName = filePath;
            } else {
                throw new Exception("没有输入文件路径");
            }
        } else {
            fileName = filePath.substring(len + 1);
            String type = filePath.substring(0, len);
            String[] typeArray = type.split("/");
            for (String s : typeArray) {
                if (!checkDirectory(ftp, s)) {
                    ftp.mkdir(s);
                }
            }
        }
        ftp.put(inStream, fileName);
    }

    /**
     * 删除ftp文件
     *
     * @param filePath 文件路径
     * @throws Exception
     */
    public void deleteFile(String filePath) throws Exception {
        String fileName = "";
        filePath = StringUtils.removeStart(filePath, "/");
        int len = filePath.lastIndexOf("/");
        if (len == -1) {
            if (filePath.length() > 0) {
                fileName = filePath;
            } else {
                throw new Exception("没有输入文件路径");
            }
        } else {
            fileName = filePath.substring(len + 1);

            String type = filePath.substring(0, len);
            String[] typeArray = type.split("/");
            for (String s : typeArray) {
                if (checkDirectory(ftp, s)) {
                    ftp.chdir(s);
                }
            }
        }
        ftp.delete(fileName);
    }

    /**
     * 切换目录
     *
     * @param path
     * @throws Exception
     */
    public void changeDirectory(String path) {
        if (!ValidateUtils.isEmpty(path)) {
            try {
                ftp.chdir(path);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

如何使用

    public static void main(String[] args) {
        try {
            // 从ftp下载文件
            FtpHelper ftp = new FtpHelper("127.0.0.1", 21, "root", "123456");
            File file = new File("D:\1.doc");
            ftp.uploadFile(file, "test/weradsfad2.doc");
            ftp.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

到此这篇关于SpringBoot项目集成FTP的方法步骤的文章就介绍到这了,更多相关SpringBoot集成FTP内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • java编程实现邮件定时发送的方法

    java编程实现邮件定时发送的方法

    这篇文章主要介绍了java编程实现邮件定时发送的方法,涉及Java基于定时器实现计划任务的相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下
    2015-11-11
  • 使用SpringBoot整合Jpa的过程详解

    使用SpringBoot整合Jpa的过程详解

    SpringBoot是一种快速开发框架,它简化了Java应用程序的开发过程,而Jpa是Java持久化规范的一种实现,将SpringBoot与Jpa整合可以更加方便地进行数据库操作,提高开发效率,本文将介绍如何使用Spring Boot整合Jpa,帮助读者快速上手并应用于实际项目中
    2023-12-12
  • Spring 零基础入门WebFlux框架体系

    Spring 零基础入门WebFlux框架体系

    Spring5发布有两年了,随Spring5一起发布了一个和Spring WebMvc同级的Spring WebFlux。这是一个支持反应式编程模型的新框架体系。反应式模型区别于传统的MVC最大的不同是异步的、事件驱动的、非阻塞的,这使得应用程序的并发性能会大大提高,单位时间能够处理更多的请求
    2022-07-07
  • springmvc处理响应数据的解析

    springmvc处理响应数据的解析

    今天小编就为大家分享一篇关于springmvc处理响应数据的解析,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
    2019-01-01
  • java实现压缩字符串和java字符串过滤

    java实现压缩字符串和java字符串过滤

    这篇文章主要介绍了java实现压缩字符串和java字符串过滤,需要的朋友可以参考下
    2014-04-04
  • java中使用数组进行模拟加密的方法

    java中使用数组进行模拟加密的方法

    这篇文章主要介绍了java中使用数组进行模拟加密的方法,需要的朋友可以参考下
    2014-08-08
  • Springmvc自定义参数转换实现代码解析

    Springmvc自定义参数转换实现代码解析

    这篇文章主要介绍了Springmvc自定义参数转换实现代码解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-07-07
  • Mybatis使用@one和@Many实现一对一及一对多关联查询

    Mybatis使用@one和@Many实现一对一及一对多关联查询

    本文主要介绍了Mybatis使用@one和@Many实现一对一及一对多关联查询,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-09-09
  • hbase访问方式之java api

    hbase访问方式之java api

    这篇文章主要介绍了hbase访问方式之java api,需要的朋友可以参考下
    2017-09-09
  • spring快速入门实例教程

    spring快速入门实例教程

    这篇文章主要介绍了spring快速入门实例,主要分析了spring的基本配置与控制反转,对于spring的学习具有一定的参考借鉴价值,需要的朋友可以参考下
    2014-12-12

最新评论