Java SFTP 递归下载文件夹和文件

2,058 阅读1分钟

代码如下

import com.jcraft.jsch.*;

import java.io.File;
import java.util.Vector;

public class DownloadRecursiveFolderFromSFTP {
    static ChannelSftp channelSftp = null;
    static Session session = null;
    static Channel channel = null;
    static String PATHSEPARATOR = "/";

    /**
     * @param args
     */
    public static void main(String[] args) {
        String SFTPHOST = "xxx.xxx.x.xxx"; // 服务器ip
        int SFTPPORT = 22; // SFTP Port Number
        String SFTPUSER = "xxx"; // 用户名
        String SFTPPASS = "xxx"; //密码
        String SFTPWORKINGDIR = "/root/test/11"; //服务器端下载目录
        String LOCALDIRECTORY = "E:\\temp"; //本地存储目录

        try {
            JSch jsch = new JSch();
            session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
            session.setPassword(SFTPPASS);
            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            session.connect(); // Create SFTP Session
            channel = session.openChannel("sftp"); // Open SFTP Channel
            channel.connect();
            channelSftp = (ChannelSftp) channel;
            channelSftp.cd(SFTPWORKINGDIR); // 在服务器端 进入到下载目录
            recursiveFolderDownload(SFTPWORKINGDIR, LOCALDIRECTORY); //

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (channelSftp != null)
                channelSftp.disconnect();
            if (channel != null)
                channel.disconnect();
            if (session != null)
                session.disconnect();

        }

    }

    /**
     *  通过文件路径下载
     * @param sourcePath
     * @param destinationPath
     * @throws SftpException
     */
    @SuppressWarnings("unchecked")
    private static void recursiveFolderDownload(String sourcePath, String destinationPath) throws SftpException {

        Vector<ChannelSftp.LsEntry> fileAndFolderList = channelSftp.ls(sourcePath); // Let list of folder content

        //循环遍历文件和文件夹
        for (ChannelSftp.LsEntry item : fileAndFolderList) {

            if (!item.getAttrs().isDir()) {
                //如果不是文件夹
                if (!(new File(destinationPath + PATHSEPARATOR + item.getFilename())).exists()
                        || (item.getAttrs().getMTime() > Long
                        .valueOf(new File(destinationPath + PATHSEPARATOR + item.getFilename()).lastModified()
                                / (long) 1000)
                        .intValue())) { // Download only if changed later.
                    new File(destinationPath + PATHSEPARATOR + item.getFilename());
                    //下载文件
                    channelSftp.get(sourcePath + PATHSEPARATOR + item.getFilename(),
                            destinationPath + PATHSEPARATOR + item.getFilename());
                }
            } else if (!(".".equals(item.getFilename()) || "..".equals(item.getFilename()))) {
                //文件夹 循环调用recursiveFolderDownload() 下载文件
                new File(destinationPath + PATHSEPARATOR + item.getFilename()).mkdirs();
                recursiveFolderDownload(sourcePath + PATHSEPARATOR + item.getFilename(),
                        destinationPath + PATHSEPARATOR + item.getFilename());
            }
        }
    }

}