我有两个控制器和一个启动它们的程序.
一个是生成数据的模拟器,另一个是分析数据.
两个控制器相互依赖,并使用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));
但是,类路径太长,cmd.exe的输出是命令行太长.
您是否知道如何使用自己的输出终端生成另一个线程或进程?
我很高兴有任何建议.
干杯
UPDATE
它现在使用标准的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());
}
}