Method Steps for SpringBoot Project Integration of FTP

  • 2021-12-04 18:44:57
  • OfStack

The catalogue is written at the front FTP Related Software Installation Start integration Introducing related jar packets
Introducing FTPUtils. java and FTPHelper. java
How to use

Write at the front

FTP is a file transfer protocol, which is widely used by developers for file transfer in the Internet.
However, we usually build a file system through FTP in the development process, which is used to store system files and so on.
At present, it is the upsurge of SpringBoot, so we will learn how SpringBoot integrates FTP, the related FTP component package, and several methods it mainly provides.

Of course, at the end of this series of articles, we will also give the exact FTP operation tool class, which is a small achievement, and I hope to share with you.

FTP Related Software Installation

I won't introduce how to install FTP here, but I can recommend some software to you as an option.
Linux version, it is recommended to use vsftpd to build FTP, only need to change the specified several configurations and add users.
Windows version, it is recommended to use Serv-U to build FTP, graphical interface, Chinese version, easy to operate.

Start integration

Introducing related jar packets

Here, we use edtFTPj for the component package related to FTP. In fact, many people chose the package of Java to realize FTP function before.
Add the following dependencies under pom. xml in our SpringBoot project.


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

Update maven for introduction, and then let's proceed to the next step.

Introducing FTPUtils. java and FTPHelper. java

Introduces two tool classes.

I will contribute 1 code here first, please refer to it as appropriate.


/**
 * Ftp  Tool class 
 */
public class FtpHelper {

    private FTPClient ftp;

    public FtpHelper() {

    }

    /**
     *  Initialization Ftp Information 
     *
     * @param ftpServer   ftp Server address 
     * @param ftpPort     Ftp Port number 
     * @param ftpUsername ftp  User name 
     * @param ftpPassword ftp  Password 
     */
    public FtpHelper(String ftpServer, int ftpPort, String ftpUsername,
                     String ftpPassword) {
        connect(ftpServer, ftpPort, ftpUsername, ftpPassword);
    }

    /**
     *  Connect to ftp
     *
     * @param ftpServer   ftp Server address 
     * @param ftpPort     Ftp Port number 
     * @param ftpUsername ftp  User name 
     * @param ftpPassword ftp  Password 
     */
    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;
        }
    }

    /**
     *  Change ftp Path 
     *
     * @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;
    }

    /**
     *  Disconnect ftp Link 
     */
    public void disconnect() {
        try {
            if (ftp.connected()) {
                ftp.quit();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     *  Read ftp File stream 
     *
     * @param filePath ftp File path 
     * @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(" No file path entered ");
            }
        } 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;
    }

    /**
     *  Upload files to ftp
     *
     * @param file      File object 
     * @param filePath  Upload path 
     * @throws Exception
     */
    public void uploadFile(File file, String filePath) throws Exception {
        InputStream inStream = new FileInputStream(file);
        uploadFile(inStream, filePath);
    }

    /**
     *  Upload files to ftp
     *
     * @param inStream  Uploaded file stream 
     * @param filePath  Upload path 
     * @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(" No file path entered ");
            }
        } 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);
    }

    /**
     *  Delete ftp Documents 
     *
     * @param filePath  File path 
     * @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(" No file path entered ");
            }
        } 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);
    }

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

/**
 * Ftp  Tool class 
 */
public class FtpHelper {

    private FTPClient ftp;

    public FtpHelper() {

    }

    /**
     *  Initialization Ftp Information 
     *
     * @param ftpServer   ftp Server address 
     * @param ftpPort     Ftp Port number 
     * @param ftpUsername ftp  User name 
     * @param ftpPassword ftp  Password 
     */
    public FtpHelper(String ftpServer, int ftpPort, String ftpUsername,
                     String ftpPassword) {
        connect(ftpServer, ftpPort, ftpUsername, ftpPassword);
    }

    /**
     *  Connect to ftp
     *
     * @param ftpServer   ftp Server address 
     * @param ftpPort     Ftp Port number 
     * @param ftpUsername ftp  User name 
     * @param ftpPassword ftp  Password 
     */
    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;
        }
    }

    /**
     *  Change ftp Path 
     *
     * @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;
    }

    /**
     *  Disconnect ftp Link 
     */
    public void disconnect() {
        try {
            if (ftp.connected()) {
                ftp.quit();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     *  Read ftp File stream 
     *
     * @param filePath ftp File path 
     * @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(" No file path entered ");
            }
        } 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;
    }

    /**
     *  Upload files to ftp
     *
     * @param file      File object 
     * @param filePath  Upload path 
     * @throws Exception
     */
    public void uploadFile(File file, String filePath) throws Exception {
        InputStream inStream = new FileInputStream(file);
        uploadFile(inStream, filePath);
    }

    /**
     *  Upload files to ftp
     *
     * @param inStream  Uploaded file stream 
     * @param filePath  Upload path 
     * @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(" No file path entered ");
            }
        } 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);
    }

    /**
     *  Delete ftp Documents 
     *
     * @param filePath  File path 
     * @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(" No file path entered ");
            }
        } 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);
    }

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

How to use


    public static void main(String[] args) {
        try {
            //  From ftp Download a file 
            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();
        }
    }

Related articles: