笔记十、Unicode文件转换GBK文件

代码如下

    /**
     * 将Unicode文件转换成GBK文件
     * @param filePath Unicode文件路径
     * @param savePath GBK文件保存路径
     */
    public static void unicodeFile2GBKFile(String filePath,String savePath){
        // 将unicode文件转换成String类型
        String str = fileToString(filePath);
        // 将unicode字符串转换成GBK字符串
        str = unicodeToGBK(str);
        // 将GBK字符串写入savePath路径的文件
        try ( FileOutputStream fos = new FileOutputStream(savePath)){
            fos.write(str.getBytes("GBK"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 将Unicode字符串转换成GBK字符串
     * @param unicodeStr Unicode字符串
     * @return GBK字符串
     */
    private static String unicodeToGBK(String unicodeStr){
        int index = 0;
        StringBuilder builder = new StringBuilder();
        int unicodeLength = unicodeStr.length();
        while(index<unicodeLength){
            if(index >= unicodeLength-1 || !"\\u".equals(unicodeStr.substring(index,index+2))){
                builder.append(unicodeStr.charAt(index));
                index++;
            }
        }
        return builder.toString();
    }

    /**
     * 将unicode文件转换成String类型
     * @param filePath unicode文件路径
     * @return Unicode字符串
     */
    private static String fileToString(String filePath){
        StringBuilder builder = new StringBuilder();
        try (BufferedReader br = new BufferedReader(
                new InputStreamReader(
                new FileInputStream(filePath),"Unicode"))){
            String str = null;
            char[] chars = new char[1024*10];
            int len = -1;
            while ((len = br.read(chars,0,len))!= -1){
                str = new String(chars,0,len);
                builder.append(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return builder.toString();
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值