我有两个控制器和一个启动它们的程序。一个是生成数据的模拟器,另一个是分析数据。两个控制器相互依赖并使用 RMI 进行通信。因此,我在另一个线程中启动模拟器,在我的主线程中启动分析器。 这工作得很好。
现在的问题是,它们都在控制台上产生了相当多的输出,我真的希望它们打印到两个不同的终端。有没有办法做到这一点?
我尝试将模拟器作为新命令行中的子进程启动(平台独立性将是下一步)
String separator = System.getProperty("file.separator");
String classpath = System.getProperty("java.class.path");
String path = System.getProperty("java.home")
+ separator + "bin" + separator + "java";
ProcessBuilder processBuilder =
new ProcessBuilder(
"\"" + path + "\"",
"-cp",
classpath,
TheEumlator.class.getName());
String command = StringUtils.join(processBuilder.command(), " ");
Process p = Runtime.getRuntime().exec(String.format("cmd /c start cmd.exe /K %s", command));
但是,classpath
is 太长了,输出cmd.exe
isThe command line is too long.
您知道如何使用自己的输出终端生成另一个线程或进程吗?我很乐意提出任何建议。
干杯
更新
我将 OlaviMustanoja 的答案与此解决方案结合在一起 http://unserializableone.blogspot.co.uk/2009/01/redirecting-systemout-and-systemerr-to.html
它现在使用标准System.out
和System.err
堆栈跟踪。此外,它会滚动。
public class ConsoleWindow implements Runnable {
private String title;
private JFrame frame;
private JTextArea outputArea;
private JScrollPane scrollPane;
public ConsoleWindow(String title, boolean redirectStreams) {
this.title = title;
this.outputArea = new JTextArea(30, 80);
this.outputArea.setEditable(false);
if (redirectStreams)
redirectSystemStreams();
}
public ConsoleWindow(String title) {
this(title, false);
}
@Override
public void run() {
frame = new JFrame(this.title);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
scrollPane = new JScrollPane(outputArea);
JPanel outputPanel = new JPanel(new FlowLayout());
outputPanel.add(scrollPane);
frame.add(outputPanel);
frame.pack();
frame.setVisible(true);
}
private void updateTextArea(final String text) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
outputArea.append(text);
}
});
}
private void redirectSystemStreams() {
OutputStream out = new OutputStream() {
@Override
public void write(int b) throws IOException {
updateTextArea(String.valueOf((char) b));
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
updateTextArea(new String(b, off, len));
}
@Override
public void write(byte[] b) throws IOException {
write(b, 0, b.length);
}
};
System.setOut(new PrintStream(out, true));
System.setErr(new PrintStream(out, true));
}
public void println(String msg) {
updateTextArea(msg + "\n");
}
public void println(Throwable t) {
println(t.toString());
}
public void print(String msg) {
updateTextArea(msg);
}
public void printStackTrace(Throwable t) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
t.printStackTrace(pw);
this.println(sw.toString());
}
}