我的应用程序有一个控制台,其中所有系统的打印流内容都被重新路由到。
我的应用程序还会输出特殊字符,特别是其他语言(亚洲语言,俄语,阿拉伯语等)
我正在使用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 ) );
}
}
这有效,打印流打印到这个jtextarea。但是,我有编码问题。 ▒, █, .نت, 览, etc
等特殊字符无法正确呈现。有些可能被硬编码到源文件中(我使用的是UTF-8),但有些可能是使用selenium webdriver从Web中提取的。
答案 0 :(得分:2)
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);
}
}