在 Java 11 中启动外部命令行进程

Start an external command line process in Java 11

我正在使用基于 CLI 的验证工具来检查一些图像文件。它 运行s 在命令提示符下,命令类似于“my_app input_file config_file”。我想将它集成到 Java 应用程序中(在 Java 11 中)。所以我需要从我的 Java 项目中 运行 它们。我尝试通过以下代码从 Java 启动应用程序:

Runtime rt = Runtime.getRuntime();
        try {
            rt.exec(new String[]{"/path/to/external/application/exefile","/c","./my_command -h"});

        } catch (IOException e) {
            e.printStackTrace();
        }

但它不提示命令行并启动应用程序。 谁能告诉我如何 运行 Java 11 中的过程?

更新:

我的外部进程现在可以正常工作了。但是我遇到了另一个问题。过程 returns 一些我需要逐行检查的输出。我需要检查它是否显示任何无效错误。如果出现无效错误,我将调用另一个外部进程。我试图使用 BufferedReader 来处理如下输出,但它没有显示任何结果。

            BufferedReader output = new BufferedReader(new InputStreamReader(process.getInputStream()));

String s = null;
            while ((s = output.readLine()) != null) {
                System.out.println(s);
            }

心灵the documentation of Runtime.exec(…):

An invocation of the form exec(cmdarray) behaves in exactly the same way as the invocation exec(cmdarray, null, null).

exec(cmdarray, null, null):


ProcessBuilder.start() is now the preferred way to start a process with a modified environment.

问题是 exec 总是为您的进程必须读取或写入的标准 I/O 创建管道,以便与新进程通信。只有 ProcessBuilder 允许以预期的方式改变该行为:

Process p = new ProcessBuilder(
    "/path/to/external/application/exefile", "/c", "./my_command -h")
    .inheritIO().start();

关键部分是inheritIO(),告诉进程构建器新进程应该继承标准输入、输出和错误通道,而不是创建管道,以使用与您的进程相同的控制台。