java中使用SFTP发送文件

本文介绍如何使用Java通过JSCH库进行SSH连接,并实现文件的上传,包括设置会话、配置SSH参数和实际操作步骤。适合对SSH和文件传输感兴趣的开发者。

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

导入依赖

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

或者jar包

import com.jcraft.jsch.*

上传文件

public static void upload(String username,String password,String host,int port,String filePath,String uploadFile) {
        Session sshSession = null;
        ChannelSftp sftp = null;
        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();
            Channel channel = sshSession.openChannel("sftp");
            channel.connect();
            sftp = (ChannelSftp) channel;
            //发送文件、
            sftp.cd(filePath);
            System.out.println("-------上传文件-------:"+uploadFile);
            File file = new File(uploadFile);
            sftp.put(new FileInputStream(file), file.getName());
            System.out.println("-------上传完成-------:"+filePath);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (sftp.isConnected()) {
                sshSession.disconnect();
                sftp.disconnect();
            }
        }
    }

测试方法

public static void main(String[] args) {
    String filePath="/test/zhanglm/";
    String host="127.0.0.1";
    int sftpPort=22;
    String username="root";
    String password="123456";
    String localFilePath="D:\\test\\";
    String fileName = "test.txt";

    upload(username,password,host,sftpPort,filePath,localFilePath + fileName);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

如我一般的人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值