ChannelSftp下载目录下所有或指定文件、ChannelSftp获取某目录下所有文件名称、InputStream转File

本文介绍如何使用Java的JSch库通过SFTP协议下载远程服务器上的文件,并提供了具体的代码实现,包括下载目录下所有文件、获取文件列表以及将InputStream转换为本地File的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ChannelSftp下载目录下所有或指定文件、ChannelSftp获取某目录下所有文件名称、InputStream转File


    /**
     * ChannelSftp下载目录下所有或指定文件
     * ChannelSftp获取某目录下所有文件名称
     * InputStream转File
     */
    public Map<String, File> downFile(String remoteDir) {
        Map<String, File> fileMap = new HashMap<>(20);
        if (StringUtil.isEmpty(remoteDir)) {
            return fileMap;
        }
        ChannelSftp channelSftp = null;
        try {
            JSch jsch = new JSch();
            Session sshSession = jsch.getSession("name", "host", 22);
            sshSession.setPassword("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);
            Iterator iterator = vector.iterator();
            while (iterator.hasNext()) {
                ChannelSftp.LsEntry file = (ChannelSftp.LsEntry) iterator.next();
                //文件名称
                String fileName = file.getFilename();
                //todo 这里可使用if或正则不下载一些文件
                InputStream inputStream = channelSftp.get(remoteDir + fileName);
                if (inputStream != null) {
                    File newFile = new File(fileName);
                    //将InputStream转File
                    FileUtils.copyToFile(inputStream, newFile);
                    fileMap.put(fileName, newFile);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (channelSftp != null) {
                channelSftp.exit();
            }
        }
        return fileMap;
    }
    


    pom.xml


        <dependency>
            <groupId>com.jcraft</groupId>
            <artifactId>jsch</artifactId>
            <version>0.1.51</version>
        </dependency>

 

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值