编写一个java 程序启动shell脚本
时间: 2023-08-11 20:58:44 浏览: 79
可以使用Java的`Runtime`类来执行shell脚本。下面是一个简单的示例程序:
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ShellScriptRunner {
public static void main(String[] args) {
try {
// 执行shell脚本的命令
String command = "sh /path/to/your/script.sh";
// 创建进程执行命令
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("Command exited with code: " + exitCode);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
```
请将`/path/to/your/script.sh`替换为您的shell脚本的实际路径。运行此程序将执行指定的shell脚本,并打印出脚本的输出以及命令的退出代码。