How to redirect all console output to a Swing JTextArea/JTextPane with the right encoding?
Solution 1
Try this code:
public class MyOutputStream extends OutputStream {
private PipedOutputStream out = new PipedOutputStream();
private Reader reader;
public MyOutputStream() throws IOException {
PipedInputStream in = new PipedInputStream(out);
reader = new InputStreamReader(in, "UTF-8");
}
public void write(int i) throws IOException {
out.write(i);
}
public void write(byte[] bytes, int i, int i1) throws IOException {
out.write(bytes, i, i1);
}
public void flush() throws IOException {
if (reader.ready()) {
char[] chars = new char[1024];
int n = reader.read(chars);
// this is your text
String txt = new String(chars, 0, n);
// write to System.err in this example
System.err.print(txt);
}
}
public static void main(String[] args) throws IOException {
PrintStream out = new PrintStream(new MyOutputStream(), true, "UTF-8");
System.setOut(out);
System.out.println("café résumé voilà");
}
}
Solution 2
You should create the PrintStream with the right encode: http://www.j2ee.me/j2se/1.5.0/docs/api/java/io/PrintStream.html#PrintStream(java.io.File, java.lang.String)
Could you please provide more code about what are you trying to do?
Admin
Updated on June 04, 2022Comments
-
Admin almost 2 years
I've been trying to redirect System.out PrintStream to a JTextPane. This works fine, except for the encoding of special locale characters. I found a lot of documentation about it (see for ex. mindprod encoding page), but I'm still fighting with it. Similar questions were posted in StackOverFlow, but the encoding wasn't addressed as far as I've seen.
First solution:
String sUtf = new String(s.getBytes("cp1252"),"UTF-8");
Second solution should use java.nio. I don't understand how to use the Charset.
Charset defaultCharset = Charset.defaultCharset() ; byte[] b = s.getBytes(); Charset cs = Charset.forName("UTF-8"); ByteBuffer bb = ByteBuffer.wrap( b ); CharBuffer cb = cs.decode( bb ); String stringUtf = cb.toString(); myTextPane.text = stringUtf
Neither solution works out. Any idea?
Thanks in advance, jgran
-
Admin over 14 yearsThanks a lot for your solution which could be quickly adapted to my own problem. Regards.
-
TheRealChx101 over 8 yearsDoes
write()
automatically callflush()
? -
gwentech over 8 years@chx101, write() does not call flush() but PrintStream does for each new line. Please note that the implementation of the flush() in the example above uses char buffer of 1024 - which is not suitable for the prod use.