Springboot sftpのファイルを読み込む

9490 ワード

1.pom依存性の追加(springbootプロジェクトベース)
  
	    com.jcraft  
	    jsch  
	    0.1.54  
   

2.application.yamlプロファイル

sftp:
   ip: 192.168.1.102
   port: 22
   username: admin
   password: admin
   root: /img #     

3.ツールクラス

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 lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

/**
 *
 */
@Slf4j
public class SFTPUtil {

    /**
     *       
     */
    private static final int DOWNLOAD_RETRY = 3;

    /**
     *              
     */
    private static final long DOWNLOAD_SLEEP = 3 * 1000;

    private static final SFTPUtil SFTP = new SFTPUtil();
    private static ChannelSftp client;
    private static Session session;

    /**
     * @return
     */
    public static SFTPUtil getInstance() {
        return SFTP;
    }

    /**
     *   SFTP  
     *
     * @param username
     * @param password
     * @param ip
     * @param port
     * @return
     */
    synchronized public ChannelSftp makeConnection(String username, String password, String ip, int port) {
        if (client == null || session == null || !client.isConnected() || !session.isConnected()) {
            try {
                JSch jsch = new JSch();
                session = jsch.getSession(username, ip, port);
                if (password != null) {
                    session.setPassword(password);
                }
                Properties config = new Properties();
                //                   ,   :(ask | yes | no)
                config.put("StrictHostKeyChecking", "no");
                session.setConfig(config);
                session.connect();
                //sftp  
                Channel channel = session.openChannel("sftp");
                channel.connect();
                client = (ChannelSftp) channel;
                log.info("sftp connected success,connect to [{}:{}], username [{}]", ip, port, username);
            } catch (JSchException e) {
                log.error("sftp connected fail,connect to [{}:{}], username [{}], password [{}], error message : [{}]", ip, port, username, password, e.getMessage());
            }

        }
        return client;
    }

    /**
     *  
     *      server 
     */
    public static void close() {
        if (client != null && client.isConnected()) {
            client.disconnect();
        }
        if (session != null && session.isConnected()) {
            session.disconnect();
        }

    }

    /**
     *       
     *
     * @param downloadFile       
     * @param saveFile           
     * @param ip               
     * @param port             
     * @param username        
     * @param password       
     * @param rootPath        
     * @return
     */
    public synchronized static File download(String downloadFile, String saveFile, String ip, Integer port, String username, String password, String rootPath) {
        boolean result = false;
        File file = null;
        Integer i = 0;
        while (!result) {
            //    
            ChannelSftp sftp = getInstance().makeConnection(username, password, ip, port);
            FileOutputStream fileOutputStream = null;
            log.info("sftp file download start, target filepath is {}, save filepath is {}", downloadFile, saveFile);
            try {
                sftp.cd(rootPath);
                file = new File(saveFile);
                if (file.exists()) {
                    file.delete();
                } else {
                    file.createNewFile();
                }
                fileOutputStream = new FileOutputStream(file);
                sftp.get(downloadFile, fileOutputStream);
                result = true;
            } catch (FileNotFoundException e) {
                log.error("sftp file download fail, FileNotFound: [{}]", e.getMessage());
            } catch (IOException e) {
                log.error("sftp file download fail, IOException: [{}]", e.getMessage());
            } catch (SftpException e) {
                i++;
                log.error("sftp file download fail, sftpException: [{}]", e.getMessage());
                if (i > DOWNLOAD_RETRY) {
                    log.error("sftp file download fail, retry three times, SftpException: [{}]", e.getMessage());
                    return file;
                }
                try {
                    TimeUnit.MILLISECONDS.sleep(DOWNLOAD_SLEEP);
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
            } finally {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            SFTPUtil.close();

        }
        return file;
    }

    /**
     *     
     *
     * @param downloadFile        
     * @param saveFile          
     * @param rootPath        
     * @return
     */
    public synchronized static File download(String downloadFile, String saveFile, String rootPath) {
        boolean result = false;
        File file = null;
        Integer i = 0;
        while (!result) {
            FileOutputStream fileOutputStream = null;
            log.info("sftp file download start, target filepath is {}, save filepath is {}", downloadFile, saveFile);
            try {
                //    、    (ChannelSftp) session.openChannel("sftp")
                client.cd(rootPath);
                file = new File(saveFile);
                if (file.exists()) {
                    file.delete();
                } else {
                    file.createNewFile();
                }
                fileOutputStream = new FileOutputStream(file);
                client.get(downloadFile, fileOutputStream);
                result = true;
            } catch (FileNotFoundException e) {
                log.error("sftp file download fail, FileNotFound: [{}]", e.getMessage());
            } catch (IOException e) {
                log.error("sftp file download fail, IOException: [{}]", e.getMessage());
            } catch (SftpException e) {
                i++;
                log.error("sftp file download fail, sftpException: [{}]", e.getMessage());
                if (i > DOWNLOAD_RETRY) {
                    log.error("sftp file download fail, retry three times, SftpException: [{}]", e.getMessage());
                    return file;
                }
                try {
                    TimeUnit.MILLISECONDS.sleep(DOWNLOAD_SLEEP);
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
            } finally {
                try {
                    if (fileOutputStream != null) {
                        fileOutputStream.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return file;
    }


}

 
4.実際の呼び出し
public class SFTP {

    @Value("${sftp.ip}")
    String ip;

    @Value("${sftp.port}")
    Integer port;

    @Value("${sftp.username}")
    String username;

    @Value("${sftp.password}")
    String password;

    @Value("${sftp.root}")
    String rootPath;

     @GetMapping("/test")
    public void test() throws IOException {
        SFTPUtil.getInstance().makeConnection(username, password, ip, port);
        File file= SFTPUtil.download(downloadFilePath, "1.txt", rootPath);
        SFTPUtil.close();
        InputStreamReader read = null;
        BufferedReader bufferedReader = null;
        String encoding = "utf-8";
        try {
            read = new InputStreamReader(new FileInputStream(file), encoding);
            bufferedReader = new BufferedReader(read);
            String lineTxt = null;
            while ((lineTxt = bufferedReader.readLine()) != null) {
                log.info("[{}] downfile is [{}] ", username, lineTxt);
                }
            read.close();
            bufferedReader.close();
            file.delete();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (read != null) {
                    read.close();
                }
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
                if (file != null && file.exists()) {
                    file.delete();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }


}

コンテンツ参照先https://blog.csdn.net/qq_17655941/article/details/80757814