springboot中java代码执行shell命令
时间: 2024-09-23 13:09:38 浏览: 38
【Spring boot配置模板】java远程执行shell命令(支持向多主机发起远程命令)
在Spring Boot中,你可以通过`ProcessBuilder`、`Runtime`类或者第三方库如`Executors`来执行Shell命令。这里以`ProcessBuilder`为例说明:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class ShellCommandExecutor {
public String executeCommand(String command) {
try {
Process process = new ProcessBuilder(command.split(" ")).start();
// 获取输出
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
StringBuilder output = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
output.append(line).append("\n");
}
reader.close();
int exitCode = process.waitFor(); // 等待命令结束并获取退出码
if (exitCode == 0) {
return output.toString(); // 如果命令成功,返回输出
} else {
throw new RuntimeException("Shell command failed with exit code: " + exitCode);
}
} catch (IOException | InterruptedException e) {
throw new RuntimeException("Failed to execute shell command", e);
}
}
}
```
在这个例子中,你首先创建一个`ProcessBuilder`实例,然后使用`start()`方法启动Shell命令。通过读取`InputStream`获取命令的输出,`waitFor()`用于等待命令执行完成。
阅读全文