使用JSCH下载SFTP文件

1 篇文章 0 订阅
package com.test;

import cn.hutool.core.util.StrUtil;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * 需引入 com.jcraft.jsch
 * <dependency>
 *   <groupId>com.jcraft</groupId>
 *   <artifactId>jsch</artifactId>
 *   <version>0.1.55</version>
 * </dependency>
 * @author jojo
 * @version 1.0
 * @date 2022/8/16 14:21
 */
@Slf4j
public class SFTPUtil {

    private static final String FTP_HOST = "127.0.0.1";
    private static final String FTP_USERNAME = "username";

    private static final String FTP_PASSWORD = "passwrod";

    private static final String DOWNLOAD_PATH = "/home/test";

    /**
     * @param remoteDir 远程目录
     * @return
     */
    public Map<String, File> downFile(String remoteDir) {
        File directory = new File(DOWNLOAD_PATH + remoteDir);
        if (!directory.exists()) {
            directory.mkdirs();
        }
        Map<String, File> fileMap = new HashMap<>(20);
        if (StrUtil.isEmpty(remoteDir)) {
            return fileMap;
        }
        ChannelSftp channelSftp = null;
        try {
            JSch jsch = new JSch();
            Session sshSession = jsch.getSession(FTP_USERNAME, FTP_HOST, 22);
            sshSession.setPassword(FTP_PASSWORD);
            Properties sshConfig = new Properties();
            //当第一次连接服务器时,自动接受新的公钥
            sshConfig.put("StrictHostKeyChecking", "no");
            sshSession.setConfig(sshConfig);
            sshSession.connect();
            Channel channel = sshSession.openChannel("sftp");
            channel.connect();
            channelSftp = (ChannelSftp) channel;
            //ls命令获取文件名列表
            Vector vector = channelSftp.ls(remoteDir);
            log.info("文件数量:" + vector.size());
            Iterator iterator = vector.iterator();
            while (iterator.hasNext()) {
                ChannelSftp.LsEntry file = (ChannelSftp.LsEntry) iterator.next();
                //文件名称
                String fileName = file.getFilename();
                log.info("fileName=" + fileName);
                if (!(".".equals(fileName)) && !("..".equals(fileName))) {
                    //todo 这里可使用if或正则不下载一些文件
                    InputStream inputStream = channelSftp.get(remoteDir + fileName);
                    if (inputStream != null) {
                        File newFile = new File(DOWNLOAD_PATH + remoteDir + fileName);
                        //将InputStream转File
                        copyToFile(inputStream, newFile);
                        fileMap.put(fileName, newFile);
                    }
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            e.printStackTrace();
        } finally {
            if (channelSftp != null) {
                channelSftp.exit();
            }
        }
        return fileMap;
    }

    private static void copyToFile(InputStream inputStream, File file)
            throws IOException {
        try (FileOutputStream outputStream = new FileOutputStream(file)) {

            int read;
            byte[] bytes = new byte[1024];

            while ((read = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, read);
            }
            // commons-io
            //IOUtils.copy(inputStream, outputStream);
        }

    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值