ProcessBuilder redirected to standard output

 ̄綄美尐妖づ 提交于 2019-12-05 09:53:34

问题


I would like to redirect a java process output towards the standard output of the parent java process.

Using the ProcessBuilder class as follows:

public static void main(String[] args) {
  ProcessBuilder processBuilder = new ProcessBuilder("cmd");
  processBuilder.directory(new File("C:"));   
  processBuilder.redirectErrorStream(true); // redirect error stream to output stream
  processBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
}

I would have expected that the outputs of "cmd", which are like:

Microsoft Windows [version 6.1.7601] Copyright (c) 2009 Microsoft Corporation. Tous droits réservés.

are displayed in the DOS console used to run the java program. But nothing is displayed at all in the DOS Console.

In the other threads of discussions, I saw solutions using a BufferedReader class: but here I would like the outputs of the process to be directly displayed in the standard output, without using any BufferedReader or "while reading loop". Is it possible?

Thanks.


回答1:


Try ProcessBuilder.inheritIO() to use the same I/O as the current Java process. Plus you can daisy chain the methods:

ProcessBuilder pb = new ProcessBuilder("cmd")
    .inheritIO()
    .directory(new File("C:"));
pb.start();



回答2:


You did miss a key piece, you actually need to start your process and wait for your output. I believe this will work,

processBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
// Start the process.
try {
  Process p = processBuilder.start();
  // wait for termination.
  p.waitFor();
} catch (IOException e) {
  e.printStackTrace();
} catch (InterruptedException e) {
  e.printStackTrace();
}


来源:https://stackoverflow.com/questions/16134864/processbuilder-redirected-to-standard-output

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!