内码转换:以 GBK 编码到 UTF-8 编码为例

近日做一程序,需要将不同内码的文字转换成为某一种统一编码的文字(例如将 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);
    }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值