如何使用正确的编码将所有控制台输出重定向到Swing JTextArea / JTextPane? [英] How to redirect all console output to a Swing JTextArea/JTextPane with the right encoding?

查看:220
本文介绍了如何使用正确的编码将所有控制台输出重定向到Swing JTextArea / JTextPane?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试将System.out PrintStream重定向到JTextPane。这是非常正常的,除了特殊语言环境字符的编码。我发现了很多关于它的文档(例如 mindprod编码页面),但是我'我仍然在与它战斗。类似的问题发布在StackOverFlow中,但是编码没有按照我的看法进行处理。

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.

第一个解决方案:

String sUtf = new String(s.getBytes("cp1252"),"UTF-8");

第二个解决方案应该使用java.nio。我不明白如何使用Charset。

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?

提前感谢
jgran

Thanks in advance, jgran

推荐答案

p>尝试这段代码:

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

}

}

这篇关于如何使用正确的编码将所有控制台输出重定向到Swing JTextArea / JTextPane?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆