近日做一程序,需要将不同内码的文字转换成为某一种统一编码的文字(例如将 GBK 编码的汉字转换为 UTF-8 编码的汉字)。网上关于不同内码文字处理的文章,大都是关于解决汉字乱码问题的。而我需要做的,类似于 UltraEdit 中的 convertion 中的功能。
开始时,尝试了诸如
new String(str.getBytes("GBK"), "UTF-8");
之类的方法。对于内码转换来说,这些方法都不是正确的。这些方法,对于解决汉字显示乱码是实用的,但是并不能正确地将 GBK 汉字映射到具有相同意义的 UTF-8 汉字上去。
我们都知道,在 JVM 内部,所有的字符串都是转换成为 Unicode 编码来处理的。我们从一个 GBK 编码的文本中读取的内容,写到另外一个 UTF-8 编码的文本文件中去,并不会出现乱码的问题。似乎可以猜测到,我们可以利用 Java IO 中的 Stream 来良好的处理内码转换的问题。为了方便起见,可以借助 Apache Commons-IO 项目中提供的实用工具来编写代码。
/* gbkString 为一 GBK 编码的字符串 */
String utf8String = IOUtils.toString(IOUtils.toInputStream(gbkString, "UTF-8"));
utf8String 中字符,皆变为 UTF-8 编码。
附,com.apache.commons.io.IOUtils 中相关代码如下:
/**
* Convert the specified string to an input stream, encoded as bytes
* using the specified character encoding.
* <p>
* Character encoding names can be found at
* <a href="http://www.iana.org/assignments/character-sets">IANA</a>.
*
* @param input the string to convert
* @param encoding the encoding to use, null means platform default
* @throws IOException if the encoding is invalid
* @return an input stream
* @since Commons IO 1.1
*/
public static InputStream toInputStream(String input, String encoding) throws IOException {
byte[] bytes = encoding != null ? input.getBytes(encoding) : input.getBytes();
return new ByteArrayInputStream(bytes);
}
开始时,尝试了诸如
new String(str.getBytes("GBK"), "UTF-8");
之类的方法。对于内码转换来说,这些方法都不是正确的。这些方法,对于解决汉字显示乱码是实用的,但是并不能正确地将 GBK 汉字映射到具有相同意义的 UTF-8 汉字上去。
我们都知道,在 JVM 内部,所有的字符串都是转换成为 Unicode 编码来处理的。我们从一个 GBK 编码的文本中读取的内容,写到另外一个 UTF-8 编码的文本文件中去,并不会出现乱码的问题。似乎可以猜测到,我们可以利用 Java IO 中的 Stream 来良好的处理内码转换的问题。为了方便起见,可以借助 Apache Commons-IO 项目中提供的实用工具来编写代码。
/* gbkString 为一 GBK 编码的字符串 */
String utf8String = IOUtils.toString(IOUtils.toInputStream(gbkString, "UTF-8"));
utf8String 中字符,皆变为 UTF-8 编码。
附,com.apache.commons.io.IOUtils 中相关代码如下:
/**
* Convert the specified string to an input stream, encoded as bytes
* using the specified character encoding.
* <p>
* Character encoding names can be found at
* <a href="http://www.iana.org/assignments/character-sets">IANA</a>.
*
* @param input the string to convert
* @param encoding the encoding to use, null means platform default
* @throws IOException if the encoding is invalid
* @return an input stream
* @since Commons IO 1.1
*/
public static InputStream toInputStream(String input, String encoding) throws IOException {
byte[] bytes = encoding != null ? input.getBytes(encoding) : input.getBytes();
return new ByteArrayInputStream(bytes);
}