上面那段代码需要修改 如果服务器中的jar包存在,需要先备份再删除
时间: 2023-08-13 14:02:30 浏览: 107
好的,您可以使用以下代码实现:
```java
import com.jcraft.jsch.*;
import java.io.*;
public class SFTPUploader {
public static void main(String[] args) {
String user = "username";
String password = "password";
String host = "hostname";
int port = 22;
String jarFilePath = "/local/path/to/jar/file.jar";
String templateFolderPath = "/local/path/to/template/folder";
String remoteJarFilePath = "/remote/path/to/jar/file.jar";
String remoteTemplateFolderPath = "/remote/path/to/template/folder";
try {
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, port);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
ChannelSftp channelSftp = (ChannelSftp) session.openChannel("sftp");
channelSftp.connect();
// Backup and delete the existing jar file if it exists
if (channelSftp.stat(remoteJarFilePath) != null) {
String backupJarFilePath = remoteJarFilePath + ".bak";
channelSftp.rename(remoteJarFilePath, backupJarFilePath);
System.out.println("Backed up existing jar file to " + backupJarFilePath);
}
// Upload the new jar file
File jarFile = new File(jarFilePath);
if (jarFile.exists()) {
channelSftp.put(jarFilePath, remoteJarFilePath);
System.out.println("Uploaded new jar file to " + remoteJarFilePath);
} else {
System.out.println("Jar file not found at " + jarFilePath);
}
// Upload the template files
File templateFolder = new File(templateFolderPath);
if (templateFolder.exists() && templateFolder.isDirectory()) {
File[] templateFiles = templateFolder.listFiles();
for (File templateFile : templateFiles) {
if (templateFile.isFile()) {
channelSftp.put(templateFile.getAbsolutePath(), remoteTemplateFolderPath + "/" + templateFile.getName());
}
}
System.out.println("Uploaded template files to " + remoteTemplateFolderPath);
} else {
System.out.println("Template folder not found at " + templateFolderPath);
}
channelSftp.disconnect();
session.disconnect();
} catch (JSchException | SftpException e) {
e.printStackTrace();
}
}
}
```
在原来的基础上,增加了以下代码:
```java
// Backup and delete the existing jar file if it exists
if (channelSftp.stat(remoteJarFilePath) != null) {
String backupJarFilePath = remoteJarFilePath + ".bak";
channelSftp.rename(remoteJarFilePath, backupJarFilePath);
System.out.println("Backed up existing jar file to " + backupJarFilePath);
}
```
该代码用于备份并删除服务器上已有的 jar 文件,如果服务器上不存在该文件,则不进行操作。如果您不需要备份文件,可以直接使用以下代码删除文件:
```java
// Delete the existing jar file if it exists
if (channelSftp.stat(remoteJarFilePath) != null) {
channelSftp.rm(remoteJarFilePath);
System.out.println("Deleted existing jar file at " + remoteJarFilePath);
}
```
阅读全文