0

好的,我尝试了十几种不同的方法,但都没有成功。我想执行一个自定义 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% 有关。回过头来...

编辑--> 结果是这个自定义 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);
  }

它的工作原理就像一个热死的。:)

4

1 回答 1

2

你不需要线条

command.add("cmd");
command.add("/c");

这只需要批处理文件。我宁愿指定可执行文件的完整路径。

也许输出在stderr上?尝试替换p.getInputStream()p.getErrorStream().

于 2011-09-28T09:18:04.467 回答