gpt4 book ai didi

java - 无法通过java运行cmd命令

转载 作者:行者123 更新时间:2023-11-30 08:13:00 24 4
gpt4 key购买 nike

我有一个名为 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 控制台窗口中得到了正确的输出 -

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 ,看来最后一个选项是不可能的。

关于java - 无法通过java运行cmd命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30094866/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com