java实现sftp上传文件到服务器

本文介绍了一种使用Java实现SFTP文件上传的方法。通过JSch和trilead-ssh2库,文章详细展示了如何配置SFTP连接并上传文件到指定目录。

1、依赖

 <dependency>
     <groupId>com.jcraft</groupId>
     <artifactId>jsch</artifactId>
     <version>0.1.49</version>
</dependency>
<dependency>
     <groupId>com.trilead</groupId>
     <artifactId>trilead-ssh2</artifactId>
     <version>1.0.0-build222</version>
</dependency>

2、代码

 /**
     * sftp上传单个文件
     *
     * @param host     主机
     * @param port     端口
     * @param username 用户名
     * @param password 密码
     * @param directory  上传的目录
     *  @param uploadFile 要上传的文件
     * @return
     */
    public static boolean sftpUploadFile(String host, int port, String username, String password,String directory, String uploadFile) {
        ChannelSftp sftp = null;
        Session sshSession=null;
        Channel channel=null;
        boolean flag=true;
        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.info("SFTP Session connected.");
            channel = sshSession.openChannel("sftp");
            channel.connect();
            sftp = (ChannelSftp) channel;
            sftp.cd(directory);
            File file = new File(uploadFile);
            FileInputStream fileInputStream = new FileInputStream(file);
            sftp.put(fileInputStream, file.getName());
            fileInputStream.close();
            System.out.println("上传服务器成功");
        } catch (Exception e) {
            flag=false;
        }finally {
            sftp.disconnect();
            sshSession.disconnect();
            channel.disconnect();
        }
        return flag;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值