Java代码执行Linux下shell脚本
时间: 2023-06-30 11:27:19 浏览: 79
可以使用Java的Runtime类来执行Linux下的shell脚本,示例代码如下:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class ExecuteShellScript {
public static void main(String[] args) {
try {
// 指定要执行的shell脚本的路径
String scriptPath = "/path/to/script.sh";
// 创建Runtime实例
Runtime runtime = Runtime.getRuntime();
// 执行shell脚本
Process process = runtime.exec(scriptPath);
// 获取shell脚本的输出信息
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
// 等待shell脚本执行完毕
int exitCode = process.waitFor();
System.out.println("Shell script executed with exit code " + exitCode);
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
在上面的示例代码中,我们通过Runtime类的exec()方法来执行指定路径下的shell脚本。我们还通过Process类的getInputStream()方法获取shell脚本的输出信息,并通过BufferedReader类来读取输出信息。最后,我们使用Process类的waitFor()方法来等待shell脚本执行完毕,并获取脚本的退出码。