有没有任何免费的Java库可以用来将一个编码的字符串转换为另一个编码,类似于 iconv
?我正在使用Java版本1.3。
有没有任何免费的Java库可以用来将一个编码的字符串转换为另一个编码,类似于 iconv
?我正在使用Java版本1.3。
CharsetDecoder
应该是你要找的东西,对吧?
许多网络协议和文件使用以字节为导向的字符集存储其字符,例如ISO-8859-1
(ISO-Latin-1
)。
然而,Java的本地字符编码是Unicode UTF16BE(十六位UCS转换格式,大端字节顺序)。
请参阅Charset
。这并不意味着UTF16
是默认字符集(即:默认的“十六位Unicode代码单元序列与字节序列之间的映射”):
// Create the encoder and decoder for ISO-8859-1
Charset charset = Charset.forName("ISO-8859-1");
CharsetDecoder decoder = charset.newDecoder();
CharsetEncoder encoder = charset.newEncoder();
try {
// Convert a string to ISO-LATIN-1 bytes in a ByteBuffer
// The new ByteBuffer is ready to be read.
ByteBuffer bbuf = encoder.encode(CharBuffer.wrap("a string"));
// Convert ISO-LATIN-1 bytes in a ByteBuffer to a character ByteBuffer and then to a string.
// The new ByteBuffer is ready to be read.
CharBuffer cbuf = decoder.decode(bbuf);
String s = cbuf.toString();
} catch (CharacterCodingException e) {
}
如果你把Unicode看作一个字符集(它实际上就是这样——基本上是所有已知字符的编号集),那么它会变得容易得多。你可以将其编码为UTF-8(每个字符1-3个字节,具体取决于字符)或者UTF-16(每个字符2个字节或者使用代理对4个字节)。
在很久以前,Java使用UCS-2来编码Unicode字符集。这种编码方式只能处理每个字符2个字节,现在已经过时了。添加代理对并升级到UTF-16是一种相当明显的hack。
很多人认为他们应该一开始就使用UTF-8。当Java最初编写时,Unicode已经有超过65535个字符了...