我一直在尝试将 System.out PrintStream 重定向到 JTextPane。除了特殊区域设置字符的编码之外,这工作得很好。我找到了很多关于它的文档(参见 ex.Mindprod 编码页面),但我仍在与之斗争。 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à");
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)