或者我坚持:
String s = new String(new byte[0], Charset.forName("ISO-8859-1"));
// or ISO_8859_1, or LATIN-1 or ... still no constants for those
for (String string : strings) { // those are ISO-8959-1 encoded
s += string; // hopefully this preserves the encoding (?)
}
答案 0 :(得分:13)
字符串始终以Java格式编码UTF-16。它们只是 char
值的序列,它们是UTF-16代码单元。当您为String(byte[], String)
构造函数指定编码时,它只是说明如何将字节解码为文本 - 之后将丢弃编码。
如果您需要保留编码,则需要创建自己的类,以便将Charset
和String
放在一起。我不能说我曾经想过这样做 - 你确定你需要吗?
(所以你的“卡住”代码无论如何都不会起作用 - 而且效率也很低。)
答案 1 :(得分:2)
如何将转换器与缓存一起使用:
public static void main(String args[]) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream(1<<10);
OutputStreamWriter osw = null;
try {
osw = new OutputStreamWriter(baos, "UTF-8");
} catch (UnsupportedEncodingException ex) {
}
osw.write("Привет!");
osw.flush();
System.out.println("Hello: " + baos.toString("UTF-8"));
}