Basic fileUpload skills are essential because there are many upload and download functions in the business. Of course, downloading and parsing files from an Sftp server is different from downloading files from a normal file server. Next, I’ll take notes step by step.

1. Import dependency packages

<! -- https://mvnrepository.com/artifact/com.jcraft/jsch --> <dependency> <groupId>com.jcraft</groupId> < artifactId > JSCH < / artifactId > < version > 0.1.54 < / version > < / dependency >Copy the code

2. Implement tool classes

JSCH Usually uses password and key authentication to log in to the SFTP server.

import com.jcraft.jsch.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.Properties;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

@Slf4j
// This annotation is used to hand this class over to Spring management, i.e. make it scannable by the Springboot boot class
@Component
public class SFtpUtil {

    public static final String NO_FILE = "No such file";

    private ChannelSftp sftp = null;

    private Session sshSession = null;

    private String username;

    private String password;

    private String host;

    private int port;
	// Enter your password and account IP address
    public SFtpUtil(a) {
        this.username = "* * * * * * *";
        this.password = "* * * * * * *";
        this.host = "* * * * * * *";
        this.port = 22;
    }

    /** * Connect to the SFTP server **@returnChannelSftp SFTP type */
    public ChannelSftp connect(a) {
        log.info("FTP connection started host=" + host + "port" + port + "username=" + username);
        JSch jsch = new JSch();
        try {
            jsch.getSession(username, host, port);
            sshSession = jsch.getSession(username, host, port);
            log.info("ftp---Session created.");
            sshSession.setPassword(password);
            Properties properties = new Properties();
            properties.put("StrictHostKeyChecking"."no");
            sshSession.setConfig(properties);
            sshSession.connect();
            log.info("ftp---Session connected.");
            Channel channel = sshSession.openChannel("sftp");
            channel.connect();
            log.info("Opening Channel.");
            sftp = (ChannelSftp) channel;
            log.info("ftp---Connected to " + host);
        } catch (JSchException e) {
            throw new BadRequestException(null, SFtpUtil.class.getSimpleName(), Abnormal "connect" + e.getMessage());
        }
        return sftp;
    }
Copy the code

3. Single download method

/** * Download a single file *@paramDirectory Remote download directory (end with path symbol) *@paramThe file name remoteFileName FTP server Such as: XXX. TXT | | XXX. TXT. Zip *@paramLocalFile localFile path, for example, D:\\xxx.txt *@return
     * @throwsBadRequestException // Custom exception */
public File downloadFile(String directory, String remoteFileName, String localFile){
        log.info("FTP download file" + remoteFileName + "Start");
        connect();
        File file = null;
        OutputStream output = null;
        try {
            file = new File(localFile);
            if (file.exists()) {
                file.delete();
            }
            boolean newFile = file.createNewFile();
            // Go to the FTP server file directory
            sftp.cd(directory);
            output = new FileOutputStream(file);
            sftp.get(remoteFileName, output);
            log.info("DownloadFile:" + remoteFileName + "success from sftp");
        } catch (SftpException e) {
            if (e.toString().equals(NO_FILE)) {
                log.info("SFTP failed to download file" + directory + remoteFileName + "Doesn't exist.");
                throw new BadRequestException(null, SFtpUtil.class.getSimpleName(), "FTP file download failed" + directory + remoteFileName + "Doesn't exist.");
            }
            throw new BadRequestException(null,SFtpUtil.class.getSimpleName(), "FTP directory or file is abnormal, check FTP directory and file" + e.toString());
        } catch (FileNotFoundException e) {
            throw new BadRequestException(null, SFtpUtil.class.getSimpleName(), "Local directory is abnormal, please check" + file.getPath() + e.getMessage());
        } catch (IOException e) {
            throw new BadRequestException(null, SFtpUtil.class.getSimpleName(), "Failed to create local file" + file.getPath() + e.getMessage());
        } finally {
            if(output ! =null) {
                try {
                    output.close();
                } catch (IOException e) {
                    throw new BadRequestException(null, SFtpUtil.class.getSimpleName(), "Close stream error" + e.getMessage());
                }
            }
            disconnect();
        }

        log.info("FTP file download completed");
        return file;
    }
Copy the code

4. Close the connection

public void disconnect(a) {
        if (this.sftp ! =null) {
            if (this.sftp.isConnected()) {
                this.sftp.disconnect();
                this.sftp = null;
                log.info("sftp is closed already"); }}if (this.sshSession ! =null) {
            if (this.sshSession.isConnected()) {
                this.sshSession.disconnect();
                this.sshSession = null;
                log.info("sshSession is closed already"); }}}Copy the code