一个spring项目如何执行 jar包里的shell脚本
要在Spring项目中执行一个包含在jar包中的shell脚本,你可以使用Java的Runtime类来执行命令行命令。
下面是一个示例代码,展示了如何在Spring项目中执行一个shell脚本:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ShellExecutor {
public static void main(String[] args) {
executeShellScript();
}
public static void executeShellScript() {
try {
// 获取当前类的ClassLoader
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
// 使用ClassLoader获取shell脚本的路径
String scriptPath = classLoader.getResource("script.sh").getPath();
// 构建命令行命令
String command = "sh " + scriptPath;
// 执行命令
Process process = Runtime.getRuntime().exec(command);
// 获取命令执行的输出结果
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
// 等待命令执行完成
int exitCode = process.waitFor();
// 输出命令的退出码
System.out.println("Exit Code: " + exitCode);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
在上面的示例代码中,我们首先获取了shell脚本的路径,并构建了一个命令行命令来执行该脚本。然后,我们使用Runtime类的exec方法执行该命令,并通过Process对象获取命令执行的输出结果。最后,我们等待命令执行完成,并输出命令的退出码。
请注意,上述示例代码假设shell脚本文件名为"script.sh",并放置在classpath下的根目录中。你需要根据你的实际情况修改脚本的路径和名称
原文地址: http://www.cveoy.top/t/topic/hSgz 著作权归作者所有。请勿转载和采集!