Java 执行 Windows 命令行并等待结果
在开发 Java 应用程序时,我们经常需要执行一些外部命令行工具,比如 Windows 系统的命令行工具。本文将介绍如何在 Java 中执行 Windows 命令行并等待其执行结果。
执行外部命令
在 Java 中,我们可以使用 Runtime.getRuntime().exec(String command)
方法来执行外部命令。这个方法会返回一个 Process
对象,我们可以通过这个对象获取命令的输出和错误信息。
示例代码
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ExecuteCommand {
public static void main(String[] args) {
String command = "dir";
try {
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("命令执行完毕,退出码:" + exitCode);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
使用 waitfor 等待命令执行完毕
Process
对象的 waitFor()
方法会阻塞当前线程,直到进程终止。这个方法返回一个整数,表示进程的退出码。
示例代码
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class WaitForCommand {
public static void main(String[] args) {
String command = "ping www.baidu.com -n 4";
try {
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("命令执行完毕,退出码:" + exitCode);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
序列图
以下是执行命令并等待结果的序列图:
sequenceDiagram
participant J as Java
participant C as Command
participant P as Process
J->>C: 执行命令
C->>P: 创建进程
P->>J: 返回进程对象
J->>P: 读取输出
P->>J: 返回输出
J->>P: 调用 waitFor()
P->>J: 等待进程结束
P->>J: 返回退出码
总结
通过本文,我们学习了如何在 Java 中执行 Windows 命令行并等待其执行结果。我们使用了 Runtime.getRuntime().exec(String command)
方法来执行命令,并使用 Process
对象的 waitFor()
方法来等待命令执行完毕。这种方法在处理需要同步执行的外部命令时非常有用。
在实际开发中,我们可以根据需要选择不同的命令行工具,并通过 Java 程序来控制它们的执行。这为我们提供了一种灵活的方式来扩展应用程序的功能。