java 异步执行bash命令
时间: 2023-07-04 21:23:03 浏览: 102
异步java编程
要在Java中异步执行Bash命令,可以使用Java的ProcessBuilder类和Runtime类。
使用ProcessBuilder类:
```java
ProcessBuilder processBuilder = new ProcessBuilder("bash", "-c", "your_bash_command");
processBuilder.redirectErrorStream(true);
Process process = processBuilder.start();
// 异步读取输出
InputStream inputStream = process.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
while (true) {
String line = reader.readLine();
if (line == null) {
break;
}
System.out.println(line);
}
// 等待命令执行结束
int exitCode = process.waitFor();
System.out.println("exit code: " + exitCode);
```
使用Runtime类:
```java
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("bash -c your_bash_command");
// 异步读取输出
InputStream inputStream = process.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
while (true) {
String line = reader.readLine();
if (line == null) {
break;
}
System.out.println(line);
}
// 等待命令执行结束
int exitCode = process.waitFor();
System.out.println("exit code: " + exitCode);
```
注意,以上代码只是演示如何异步执行Bash命令,实际使用时需要根据具体情况调整。
阅读全文