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();
        }
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.

使用 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();
        }
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.

序列图

以下是执行命令并等待结果的序列图:

Process Command Java Process Command Java 执行命令 创建进程 返回进程对象 读取输出 返回输出 调用 waitFor() 等待进程结束 返回退出码

总结

通过本文,我们学习了如何在 Java 中执行 Windows 命令行并等待其执行结果。我们使用了 Runtime.getRuntime().exec(String command) 方法来执行命令,并使用 Process 对象的 waitFor() 方法来等待命令执行完毕。这种方法在处理需要同步执行的外部命令时非常有用。

在实际开发中,我们可以根据需要选择不同的命令行工具,并通过 Java 程序来控制它们的执行。这为我们提供了一种灵活的方式来扩展应用程序的功能。