JAVA封装GBK文件转换为UTF-8

本文介绍了一种将GBK编码的文件转换为UTF-8编码的方法,通过使用Java编程语言实现,包括读取文件、转换编码并写入新文件的完整流程。此方法已在实际项目中验证稳定。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

网上参考了资料,见本文末尾。感谢前辈的探索,我在他们基础上,进行了优化调整,并且验证测试稳定后,用在自己项目。不敢独享,特别发布,供同行评议。

GBK转换为UTF8代码如下:

 public static boolean GBKfileToUTF8(String filePath) {

        // 以GBK格式,读取文件
        try {
            try (FileInputStream fis = new FileInputStream(filePath); 
                    InputStreamReader isr = new InputStreamReader(fis, "GBK"); 
                    BufferedReader br = new BufferedReader(isr)) {
                String str;

                // 创建StringBuffer字符串缓存区
                StringBuilder sb = new StringBuilder();

                // 通过readLine()方法遍历读取文件
                while ((str = br.readLine()) != null) {
                    // 使用readLine()方法无法进行换行,需要手动在原本输出的字符串后面加"\n"或"\r"
                    str += "\n";
                    sb.append(str);
                }
                String str2 = sb.toString();

                // 以UTF-8格式写入文件,file.getAbsolutePath()即该文件的绝对路径,false代表不追加直接覆盖,true代表追加文件
                File file = new File(filePath);
                try (FileOutputStream fos = new FileOutputStream(file.getAbsolutePath(), false); 
                        OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8")) {
                    osw.write(str2);
                    osw.flush();
                }
            }
            return true;
        } catch (FileNotFoundException e) {
            log.debug("FileNotFoundException:" + e.toString());
            return false;

        } catch (UnsupportedEncodingException e) {
            log.debug("UnsupportedEncodingException:" + e.toString());
            return false;

        } catch (IOException e) {
            log.debug("IOException:" + e.toString());
            return false;

        }

    }

测试调用该方法代码如下:

 System.out.println("GBKfileToUTF8");
        String filePath = "E:\\cheleon\\ServerDataTableAllDataSummary20190603.csv";
       
        boolean result = TpTaskUtil.GBKfileToUTF8(filePath);

 

 

 

 

 

 

 

参考的URL如下:

https://blog.youkuaiyun.com/weixin_42038771/article/details/80490505

https://blog.youkuaiyun.com/guying4875/article/details/81034022

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值