Get Command Prompt Output to String In Java

前端 未结 3 1442
春和景丽
春和景丽 2020-12-16 23:19

I need a java method that will read command prompt output and store it into a String to be read into Java.

This is what I have so far but isn\'t working right.

3条回答
  •  感动是毒
    2020-12-17 00:02

    Assuming you use Runtime.exec() to start your external process, giving you a Process object, there are three relevant methods on that object: getOutputStream(), getInputStream(), and getErrorStream().

    I think it is easy to get confused about these -- you are probably thinking that you want to see the process's output, so therefore an "output stream" is what you want. But the thing you need to remember is that the naming of these objects is from the Java code's perspective -- an OutputStream is for Java to write output to, while an InputStream is for Java to read input from. The output of your external process is, from Java's perspective, input.

    So you would use getInputStream() and call appropriate methods on the InputStream returned by it to read the output. You also may want to use getErrorStream() to ensure that you are not missing anything because it is written to standard error.

提交回复
热议问题