JAVA上传文件到SFTP服务器

public void SftpUpload(String filePath, String sftpDirectory, String reportUrl, Integer sftpPort, String sftpUser, String sftpPassword, String name, String newName) {
            //filePath 本地压缩包路径 reportUrl服务器IP sftpPort 端口号 sftpUser账号 sftpPassword 密码 name 上传中目标服务器文件名称 newName上传完成后文件名称
            String sftpCatalogue = "/" + sftpDirectory + "/"; //上传服务器目录
            JSch jsch = new JSch();
            Session session = null;
            Channel channel = null;
            ChannelSftp channelSftp = null;

            try {
                // 建立SSH会话
                session = jsch.getSession(sftpUser, reportUrl, sftpPort);
                session.setConfig("StrictHostKeyChecking", "no");
                session.setPassword(sftpPassword);
                session.connect();

                // 开启SFTP通道
                channel = session.openChannel("sftp");
                channel.connect();
                channelSftp = (ChannelSftp) channel;

                // 将本地文件上传到服务器指定目录
                File file = new File(filePath);
                channelSftp.put(file.getAbsolutePath(),  sftpCatalogue + name);
//                channelSftp.put(filePath, sftpCatalogue + name);

                // 上传成功后 重命名服务器压缩包名称
                channelSftp.rename(sftpCatalogue + name, sftpCatalogue + newName);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                // 关闭通道和会话
                if (channelSftp != null) {
                    channelSftp.exit();
                }
                if (channel != null) {
                    channel.disconnect();
                }
                if (session != null) {
                    session.disconnect();
                }
            }
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值