如何使用正确的编码将所有控制台输出重定向到Swing JTextArea/JTextPane?

6 java encoding nio stdout

我一直在尝试将System.out PrintStream重定向到JTextPane.这种方法很好,除了特殊区域设置字符的编码.我发现了很多关于它的文档(参见前面的mindprod编码页面),但我仍然在与之抗争.在StackOverFlow中发布了类似的问题,但据我所见,编码没有得到解决.

第一解决方案

String sUtf = new String(s.getBytes("cp1252"),"UTF-8");
Run Code Online (Sandbox Code Playgroud)

第二个解决方案应该使用java.nio.我不明白如何使用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
Run Code Online (Sandbox Code Playgroud)

两种解决方案都没有成功.任何的想法?

谢谢你,jgran

Vil*_*kas 5

试试这段代码:

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à");

}

}
Run Code Online (Sandbox Code Playgroud)