gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:19:39 26 4
gpt4 key购买 nike

我一直在尝试将 System.out PrintStream 重定向到 JTextPane。这工作正常,除了特殊语言环境字符的编码。我找到了很多关于它的文档(参见 mindprod encoding page ),但我仍在与它作斗争。 StackOverFlow 中发布了类似的问题,但据我所知,编码并未得到解决。

第一种解决方案:

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

第二种解决方案应该使用 java.nio。我不明白如何使用字符集。

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

这两种解决方案都行不通。有什么想法吗?

提前致谢,杰格兰

最佳答案

试试这段代码:

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

}

}

关于java - 如何使用正确的编码将所有控制台输出重定向到 Swing JTextArea/JTextPane?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1522444/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com