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();
}
}
}
JAVA上传文件到SFTP服务器
最新推荐文章于 2025-03-17 00:17:59 发布
1154

被折叠的 条评论
为什么被折叠?



