问题描述
我编写了下面的java代码,它执行另一个名为Newsworthy_RB的java程序。
I have written the java code below, which executes another java program named "Newsworthy_RB".
Newsworthy_RB.java包含System.out.printlln()和System.err.println()语句。
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.
下面的程序只打印out.println()语句而不是err.println()语句。
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 for Runtime
:
在 ProcessBuilder
你有一个非常方便的方法叫做:
In ProcessBuilder
you have a very convenient method called redirectErrorStream
:
如果此属性为true,则此对象的start()方法随后启动的子进程生成的任何错误输出将与标准输出合并,以便可以使用Process.getInputStream()方法读取它们。这样可以更容易地将错误消息与相应的输出相关联。初始值为false。
If this property is true, then any error output generated by subprocesses subsequently started by this object's start() method will be merged with the standard output, so that both can be read using the Process.getInputStream() method. This makes it easier to correlate error messages with the corresponding output. The initial value is false.
如何输出标准错误和标准输出的完整示例:
A complete example of how to output both standard error and standard out:
import java.io.*;
public class Test {
public static void main(String... args) throws IOException {
ProcessBuilder pb =
new ProcessBuilder("java", "-cp", "yourClassPath", "HelloWorld");
pb.redirectErrorStream(true);
Process proc = pb.start();
Reader reader = new InputStreamReader(proc.getInputStream());
int ch;
while ((ch = reader.read()) != -1)
System.out.print((char) ch);
reader.close();
}
}
对您的更新的回复:不,代码
Response to your update: No, the code with
while ((c = in1.read()) != -1 || (c = in2.read()) != -1)
不起作用,因为 read()
是一种阻塞方法,你只有一个线程。您唯一的选择是每个输入流使用一个线程,或者(最好)使用 ProcessBuilder.redirectErrorStream
将两个输入流合并为一个。
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, using ProcessBuilder.redirectErrorStream
.
这篇关于如何让java程序同时打印out.println()和err.println()语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!