I have written the java code below, which executes another java program named “Newsworthy_RB”.
Newsworthy_RB.java contains both the System.out.printlln() and System.err.println() statements.
I want both the outputs to be printed in the command prompt console.
What has to be done inorder to obtain the same.
The below program just prints the out.println() statements and not the err.println() statements.
Kindly let me know whether the code below will function as i expect?
command = "java -cp .:../sqljdbc.jar SetHash Newsworthy_RB";
Process child1 = Runtime.getRuntime().exec(command);
InputStream in1 = child1.getErrorStream();
InputStream in2 = child2.getInputStream();
while ((c = in1.read()) != -1 || (c = in2.read()) != -1) {
System.out.print((char)c);
}
First of all, the preferred way of starting external programs is through
ProcessBuilder. It is even mentioned in the docs forRuntime:In
ProcessBuilderyou have a very convenient method calledredirectErrorStream:A complete example of how to output both standard error and standard out:
Response to your update: No, the code with
will not work, since
read()is a blocking method and you only have one thread. Your only option is to use one thread per input-stream, or, (preferrably) merge the two input-streams into one, usingProcessBuilder.redirectErrorStream.