SpringBoot项目集成FTP

简介: FTP是一个文件传输协议,被开发人员广泛用于在互联网中文件传输的一套标准协议。而我们通常在开发过程中也要通过FTP来搭建文件系统,用于存储系统文件等。目前正值SpringBoot热潮,所以接下来会一起学习一下SpringBoot如何集成FTP,以及相关的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 工具类
 */
@Slf4j
public class FtpUtils {
    public static FtpHelper getFtpHelper() {
        String ftpServer = ConfigService.getConfig("ftpServer");
        int ftpPort = Integer.parseInt(Objects.requireNonNull(ConfigService.getConfig("ftpPort")));
        String ftpUsername = ConfigService.getConfig("ftpUsername");
        String ftpPassword = ConfigService.getConfig("ftpPassWord");
        return new FtpHelper(ftpServer, ftpPort, ftpUsername, ftpPassword);
    }
    /**
     * 上传文件到Ftp
     *
     * @param in
     * @param path
     */
    public static void uploadFile(InputStream in, String path) throws IOException {
        if (null == in) {
            log.error("文件不能为空!");
            return;
        }
        if (ValidateUtils.isEmpty(path)) {
            log.error("上传路径不能为空!");
            return;
        }
        FtpHelper ftp = getFtpHelper();
        try {
            ftp.uploadFile(in, path);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            in.close();
            ftp.disconnect();
        }
    }
    /**
     * 刪除Ftp文件
     */
    public static void deleteFile(String path) {
        if (ValidateUtils.isEmpty(path)) {
            log.error("上传路径不能为空!");
            return;
        }
        FtpHelper ftp = getFtpHelper();
        try {
            ftp.deleteFile(path);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ftp.disconnect();
        }
    }
    /**
     * 读取文件
     *
     * @param path
     * @return
     */
    public static InputStream readFile(String path) {
        if (ValidateUtils.isEmpty(path)) {
            log.error("上传路径不能为空!");
            return null;
        }
        FtpHelper ftp = getFtpHelper();
        InputStream in = null;
        try {
            in = ftp.downloadFile(path);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ftp.disconnect();
        }
        return in;
    }
    public static String getFileName(String path) {
        String name = null;
        if (!ValidateUtils.isEmpty(path)) {
            int n = path.lastIndexOf("/");
            if (n > 0) {
                name = path.substring(n + 1);
            }
        }
        return name;
    }
}
/**
 * FtpHelper
 */
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();
        }
    }
目录
相关文章
|
16天前
|
Java Linux
Springboot 解决linux服务器下获取不到项目Resources下资源
Springboot 解决linux服务器下获取不到项目Resources下资源
|
16天前
|
消息中间件 Java Kafka
Springboot集成高低版本kafka
Springboot集成高低版本kafka
|
23天前
|
NoSQL Java Redis
SpringBoot集成Redis解决表单重复提交接口幂等(亲测可用)
SpringBoot集成Redis解决表单重复提交接口幂等(亲测可用)
215 0
|
23天前
|
Java API Spring
SpringBoot项目调用HTTP接口5种方式你了解多少?
SpringBoot项目调用HTTP接口5种方式你了解多少?
78 2
|
23天前
|
前端开发 JavaScript Java
6个SpringBoot 项目拿来就可以学习项目经验接私活
6个SpringBoot 项目拿来就可以学习项目经验接私活
33 0
|
1月前
|
前端开发 Java 关系型数据库
SpringBoot+MyBatis 天猫商城项目
SpringBoot+MyBatis 天猫商城项目
55 1
|
26天前
|
Java Maven 微服务
springboot项目开启远程调试-jar包
springboot项目开启远程调试-jar包
20 0
|
28天前
|
NoSQL Java Redis
SpringBoot集成Redis
SpringBoot集成Redis
356 0
|
1月前
|
NoSQL Java Redis
小白版的springboot中集成mqtt服务(超级无敌详细),实现不了掐我头!!!
小白版的springboot中集成mqtt服务(超级无敌详细),实现不了掐我头!!!
262 1
|
1天前
|
Java 关系型数据库 数据库
【SpringBoot系列】微服务集成Flyway
【4月更文挑战第7天】SpringBoot微服务集成Flyway
【SpringBoot系列】微服务集成Flyway

热门文章

最新文章