无法通过 java 运行 cmd 命令

Not able to run cmd command through java

我有一个名为 galen.bat.bat 文件。我在 PATH 环境变量中包含了这个文件的路径。

当我运行:

galen.bat --version

cmd 中,我得到以下输出:

Galen Framework
Version: 1.6.3
JavaScript executor: Rhino 1.7 release 5 2015 01 29

我有以下 java 代码,我试图通过这些代码 运行 通过我的应用程序执行相同的命令 -

 public static void main(String[] args) throws Exception {
            ProcessBuilder builder = new ProcessBuilder(
                "cmd.exe", "/c", "galen.bat --version");
            builder.redirectErrorStream(true);
            Process p = builder.start();
            BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line;
            while (true) {
                line = r.readLine();
                if (line == null) { break; }
                System.out.println(line);
            }
        }

当我 运行 这样做时,我收到以下错误 -

'galen.bat' is not recognized as an internal or external command,
operable program or batch file.

请注意,如果我使用

ProcessBuilder builder = new ProcessBuilder(
                    "cmd.exe", "/c", "java -version");

而不是

ProcessBuilder builder = new ProcessBuilder(
                    "cmd.exe", "/c", "galen.bat --version");

然后我在我的 eclipse 控制台中得到了正确的输出 window -

java version "1.7.0_03"
Java(TM) SE Runtime Environment (build 1.7.0_03-b05)
Java HotSpot(TM) 64-Bit Server VM (build 22.1-b02, mixed mode)

为什么 galen.bat --version 不起作用?我该如何解决? 谢谢!

根据the docs

When a Java application uses a ProcessBuilder object to create a new process, the default set of environment variables passed to the new process is the same set provided to the application's virtual machine process. The application can change this set using ProcessBuilder.environment.

因此您必须在 JVM 路径中包含新路径 galen.bat 或将 ProcessBuilder.environment 更改为您的系统 PATH,但 according this answer 似乎是最后的选择不可能。