我知道這是一個非常普遍的問題,但我變得生氣了。在Java中使用Windows 1252轉換爲UTF8:使用CharsetDecoder/Encoder的空字符
我用這個代碼:
String ucs2Content = new String(bufferToConvert, inputEncoding);
byte[] outputBuf = ucs2Content.getBytes(outputEncoding);
return outputBuf;
但我讀到最好使用CharsetDecoder和CharsetEncoder(我有內容,有一些字符可能是目的地編碼外)。我剛剛寫了這個代碼,但也存在一些問題:
// Create the encoder and decoder for Win1252
Charset charsetInput = Charset.forName(inputEncoding);
CharsetDecoder decoder = charsetInput.newDecoder();
Charset charsetOutput = Charset.forName(outputEncoding);
CharsetEncoder encoder = charsetOutput.newEncoder();
// Convert the byte array from starting inputEncoding into UCS2
CharBuffer cbuf = decoder.decode(ByteBuffer.wrap(bufferToConvert));
// Convert the internal UCS2 representation into outputEncoding
ByteBuffer bbuf = encoder.encode(CharBuffer.wrap(cbuf));
return bbuf.array();
事實上這段代碼追加到緩衝空字符序列!!!!!
有人能告訴我問題在哪裏嗎?我不熟悉Java中的編碼轉換。
有沒有更好的方法來轉換Java中的編碼?
謝謝,你可能只是救了我幾個小時的挫折 – pepsi 2011-08-11 19:29:58