我的应用程序有一个控制台,所有系统的printstream内容都被重路由到该控制台。
我的应用程序还将输出特殊字符,特别是其他语言(亚洲语言,俄语,阿拉伯语等)
我使用JTextArea作为控制台输出:
consoleOutput = new JTextArea(1, 50);
DefaultCaret caret = (DefaultCaret) consoleOutput.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
Font font = new Font("Consolas", Font.PLAIN, 12);
consoleOutput.setFont(font);
JScrollPane scrollPane = new JScrollPane(consoleOutput);
this.add(scrollPane, BorderLayout.CENTER);
//CHANGE OUTPUT TO THIS CONSOLE
PrintStream out = new PrintStream(new TextAreaOutput(consoleOutput));
System.setOut(out);
System.setErr(out);
和这个类来重写printstream:
public class TextAreaOutput extends OutputStream {
JTextArea outputConsole;
public TextAreaOutput(JTextArea outputConsole) {
this.outputConsole = outputConsole;
}
@Override
public void write(int b) throws IOException {
outputConsole.append( String.valueOf( ( char )b ) );
}
}
这可以工作,printstream打印到这个jtextarea。然而,我有编码问题。像▒, █, .نت, 览, etc
这样的特殊字符不能正确呈现。有些可能会硬编码到源文件中(我使用UTF-8),但有些可能会使用selenium webdriver从web中提取。
- 这是一个可能的实现使用:
- new PrintStream(OutputStream out, boolean autoFlush, String encoding)
- ByteArrayOutputStream # toString(字符串编码)
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.Date;
import javax.swing.*;
public class TextAreaOutputStreamTest {
private final JTextArea consoleOutput = new JTextArea();
private final JTextField textField = new JTextField();
public JComponent makeUI() {
try {
OutputStream os = new TextAreaOutputStream(consoleOutput);
System.setOut(new PrintStream(os, true, "UTF-8"));
} catch (IOException ex) {
ex.printStackTrace();
}
Box box = Box.createHorizontalBox();
box.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
box.add(Box.createHorizontalGlue());
box.add(textField);
box.add(Box.createHorizontalStrut(5));
box.add(new JButton(new AbstractAction("Enter") {
@Override public void actionPerformed(ActionEvent e) {
String s = new Date().toString();
System.out.println(s + "n " + textField.getText());
}
}));
consoleOutput.setEditable(false);
JPanel p = new JPanel(new BorderLayout());
p.add(new JScrollPane(consoleOutput));
p.add(box, BorderLayout.SOUTH);
return p;
}
public static void main(String... args) {
EventQueue.invokeLater(new Runnable() {
@Override public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().add(new TextAreaOutputStreamTest().makeUI());
f.setSize(320, 240);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
class TextAreaOutputStream extends OutputStream {
private final ByteArrayOutputStream buf = new ByteArrayOutputStream();
private final JTextArea consoleOutput;
public TextAreaOutputStream(JTextArea consoleOutput) {
super();
this.consoleOutput = consoleOutput;
}
@Override public void flush() throws IOException {
consoleOutput.append(buf.toString("UTF-8"));
buf.reset();
}
@Override public void write(int b) throws IOException {
buf.write(b);
}
}