上传文件到sftp服务器

本地上传文件到SFTP服务器

代码

需要知道sftp服务器的ip,端口,用户名,密码,上传服务器的文件路径。
方法参数为文件上一级目录和要上传的本地文件路径

public void uploadSftp(String dir, String localFile){
        try {
            //1.获取会话
            JSch jSch = new JSch();
            Session session = jSch.getSession(sftpUsername, sftpAddress, sftpPort);
            session.setPassword(sftpPassword);
            Properties properties = new Properties();
            properties.put("StrictHostKeyChecking", "no");
            session.setConfig(properties);
            session.connect();
            //2.获取上传通道
            Channel channel = session.openChannel("sftp");
            channel.connect();
            ChannelSftp sftp = (ChannelSftp) channel;
            //3.上传文件
            FileInputStream inputStream;
            try {
                try {
                    sftp.cd(sftpFileUrl);
                } catch (SftpException e) {
                    logger.error("切换目录失败");
                    throw new RuntimeException(e);
                }
                String dirPath = sftpFileUrl + dir;
                if (!isDirExist(dirPath, sftp)){
                    sftp.mkdir(dirPath);
                }
                sftp.cd(dirPath);
                inputStream = new FileInputStream(localFile);
                sftp.put(inputStream, "data.json");
            } catch (Exception e) {
                logger.error("上传文件失败");
                throw new RuntimeException(e);
            }
            sftp.disconnect();
            inputStream.close();
            channel.disconnect();
            session.disconnect();
            logger.info("上传sftp服务器成功");

        } catch (Exception e) {
            logger.error("上传sftp服务器失败");
            throw new RuntimeException(e);
        }
    }
    /**
     * 判断目录是否存在
     * @param directory
     * @return
     */
    public static boolean isDirExist(String directory, ChannelSftp sftp)
    {
        boolean isDirExistFlag = false;
        try
        {
            SftpATTRS sftpATTRS = sftp.lstat(directory);
            isDirExistFlag = true;
            return sftpATTRS.isDir();
        }
        catch (Exception e)
        {
            if (e.getMessage().toLowerCase().equals("no such file"))
            {
                isDirExistFlag = false;
            }
        }
        return isDirExistFlag;
    }

参考链接

  • https://blog.csdn.net/weixin_45031612/article/details/123513850
  • https://www.csdn.net/tags/MtTaAg5sMzc3NTIxLWJsb2cO0O0O.html
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值