【发布时间】:2011-09-28 09:10:37
【问题描述】:
好的,我尝试了十几种不同的方法,但都没有成功。我想执行一个自定义 exe 并获取输出。它在命令提示符下运行良好。我让“dir”正常工作,但不是 custom.exe。代码如下:
List<String> command = new ArrayList<String>();
command.add("cmd"); // Even removed these two lines
command.add("/c"); // aka hail mary coding.
//command.add("dir");
command.add("custom.exe"); // even tried "c://custom.exe"
String line;
Process p = new ProcessBuilder(command).start();
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
System.out.println(line);
}
我根本没有输出。如果我把它放在一个批处理文件中,我会得到输出。我感觉它与 %PATH% 有关。回过头来...
EDIT--> 结果是这个自定义 exe 的输出出错了,所以要查看发生了什么,我有代码:
List<String> command = new ArrayList<String>();
command.add(System.getenv("ProgramFiles(x86)") + "\\mydir\\custom.exe";
String line;
ProcessBuilder pb = new ProcessBuilder(command);
pb.redirectErrorStream(true);
Process p = pb.start();
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
System.out.println(line);
}
而且它的工作原理非常糟糕。 :)
【问题讨论】:
-
你想用 cmd /c 实现什么?
-
您是否尝试过仅将“custom.exe”放入命令中?你不应该需要“cmd /c”,因为 Java 会自动打开流到子进程的标准输入、标准输出和标准错误。
-
我确实将“cmd /c”仅用于 dir 命令并且它有效(根据我看到的示例)。尝试使用和不使用“custom.exe”命令。都没有用。
标签: java windows processbuilder