ChannelSftp 远程下载和远程上传

这篇博客介绍了如何利用ChannelSftp实现远程文件的下载和上传,详细讲解了所需的jar包,并提供了运行前后的步骤说明,参考了相关博客资源。

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

1.需要的jar包:

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

2.话不多说上代码

package com.zte.FTP;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Vector;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import sun.dc.path.PathError;

public class FtpsFileList {
    private static final Logger LOG = LoggerFactory.getLogger(FtpsFileList.class);

    private static ChannelSftp sftp = null;
    private static Channel channel = null;
    private static Session sshSession = null;
    private static String src = "/home/ubuntu/test10257527";
    private static String localDownPath = "D:\\filepath\\download";
    private static String localUpPath = "D:\\filepath\\upfile";

    public static void main(String[] args) {

        channel = getChannel("10.62.118.102", 22, "ubuntu", "cloud");//serve Ip,port,username,pwd
        List<String> str = listFileNames(channel, src);
        System.out.println("目录下包含的文件名称为:" + str);
        for (String a : str) {
            System.out.println("文件名为:" + a);
        }

        //download file from serve
        getFileFromSftpServer(channel, src, localDownPath);

        //upload file to serve from local
        putFileToSftpServer(channel,src,localUpPath);

        closeResource(channel, sftp, sshSession);
    }

    private static List<String> listFileNames(Channel channel, String dir) {
        List<String> list = new ArrayList<String>();
        ChannelSftp sftp = null;
        try {
            sftp = (ChannelSftp) channel;
            Vector vector = sftp.ls(dir);//获取文件列表
            for (Object item : vector) {
                if (item instanceof com.jcraft.jsch.ChannelSftp.LsEntry) {
                    String fileName = ((com.jcraft.jsch.ChannelSftp.LsEntry) item).getFilename();
                    if (fileName.equals(".") || fileName.equals("..")) {
                        continue;
                    }
                    System.out.println(fileName);
                    list.add(fileName);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    private static void getFileFromSftpServer(Channel channel, String src, String localPath) {
        ChannelSftp sftp = null;

        try {
            sftp = (ChannelSftp) channel;
            Vector vector = sftp.ls(src);//获取文件目录下所有的文件
            for (Object item : vector) {
                if (item instanceof com.jcraft.jsch.ChannelSftp.LsEntry) {
                    String fileName = ((com.jcraft.jsch.ChannelSftp.LsEntry) item).getFilename();
                    if (fileName.equals(".") || fileName.equals("..")) {
                        continue;
                    }
                    System.out.println(fileName);
                    File localpath = new File(localPath);
                    File[] fileList = localpath.listFiles();
                    if (!localpath.exists()) {
                        localpath.mkdirs();
                        localPath = localpath.getPath();
                    }
                    for (File file : fileList) {
                        if (fileName.equals(file.getName())) {
                            file.delete();
                        }
                    }
                    System.out.println(localPath);
                    String localFileName = localPath + File.separator + fileName;

                    sftp.get(src + "/" + fileName, localPath);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void putFileToSftpServer(Channel channel, String src, String localPath) {
        List<String> list = new ArrayList<String>();
        try {
            sftp = (ChannelSftp) channel;
            File file = new File(localPath);
            if (!file.exists()) {
                throw new PathError("本地路径有误");
            }
            File[] files = file.listFiles();
            for (File item : files) {
                list.add(item.getName());
                System.out.println("getPath:" + item.getPath());
                sftp.put(localPath + File.separator + item.getName(), src);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static Channel getChannel(String host, int port, String username, final String password) {

        try {
            JSch jsch = new JSch();
            jsch.getSession(username, host, port);
            sshSession = jsch.getSession(username, host, port);
            sshSession.setPassword(password);
            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");
            sshSession.setConfig(sshConfig);
            sshSession.connect();
            LOG.debug("Session connected!");
            channel = sshSession.openChannel("sftp");
            channel.connect();
            LOG.debug("Channel connected!");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return channel;
    }

    private static void closeResource(Channel channel, ChannelSftp sftp, Session session) {
        if (channel != null) {
            if (channel.isConnected()) {
                channel.disconnect();
            }
        }
        if (sftp != null) {
            if (sftp.isConnected()) {
                sftp.disconnect();
            }
        }
        if (session != null) {
            if (session.isConnected()) {
                session.disconnect();
            }
        }
    }

}

运行之前:

运行之后:

参考:https://www.cnblogs.com/muliu/p/6126605.html

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值