springboot 执行linux命令
时间: 2024-11-15 11:14:49 浏览: 11
在Spring Boot应用中,如果你想执行Linux命令,你可以利用`java.lang.Runtime.getRuntime().exec()`方法或者第三方库如`Runtime`、`ProcessBuilder`或者`CommandLine`。以下是一个基本的例子:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
public class LinuxCommandExecutor {
public String executeCommand(String command) {
try {
Process process = Runtime.getRuntime().exec(command);
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();
return output.toString();
} catch (IOException e) {
throw new RuntimeException("Error executing command", e);
}
}
public static void main(String[] args) {
LinuxCommandExecutor executor = new LinuxCommandExecutor();
String result = executor.executeCommand("ls -l");
System.out.println("Command output: " + result);
}
}
```
在这个例子中,`executeCommand`方法接受一个字符串参数,该参数是你想要执行的Linux命令。它会启动一个新的进程并读取其标准输出。
阅读全文