zoukankan      html  css  js  c++  java
  • 文件字符编码的转换

          前一段时间使用Eclipse编写了多个java文件,并加了中文注释。共享给parter时,对方出现了乱码(中文无法显示)。研究发现,原来是文件的字符编码不一致。如果你没有修改过Eclipse的文件编码格式,默认是使用系统默认编码。中文Windows下默认为GB2312(或称GBK)。所以我生成的java源文件采用的是GBK编码。而对方的Eclipse文件编码格式修改成了UTF-8。考虑到以后文件需要共同修改,所以我准备将GBK编码的文件转换成UTF-8编码的文件。但是Eclipse好像没有自带这个功能,听说MyEclipse有。我也懒得上网去找插件。心想不就是字符编码不一样嘛,咱们是程序员,编程转化不成了吗?同时也巩固知识。

    转换需要使用String类的getBytes和其带字符集的构造函数。这样就偷懒了一把。

     1 private static void convertEncode(File source,String sourceCharset,File dest,String destCharset) throws IOException{
    2 //以字节形式读文件
    3 DataInputStream in=new DataInputStream(new BufferedInputStream(new FileInputStream(source)));
    4 byte[] buffer=new byte[100000];
    5 int size=in.read(buffer);
    6 in.close();
    7 //转换:sourceCharset -> destCharset
    8 String originalString=new String(buffer,0,size,sourceCharset);
    9 byte[] convert=originalString.getBytes(destCharset);
    10
    11 //以字节形式写文件
    12 DataOutputStream out=new DataOutputStream(new BufferedOutputStream(new FileOutputStream(dest)));
    13 out.write(convert);
    14 out.close();
    15 }

    这里使用字节形式读文件而没有采用字符形式主要是考虑字符形式读取文件采用的是系统默认的字符集生产String,见BufferedReader的源文件349等行

    1                    if (s == null) {
    2 str = new String(cb, startChar, i - startChar);
    3 } else {
    4 s.append(cb, startChar, i - startChar);
    5 str = s.toString();
    6 }

    这样的话就不是我想要的了。

    如果有什么好的转换方法,希望不惜赐教。



  • 相关阅读:
    Git windows换行问题
    java之aop使用及自定义注解
    Shiro授权及注解式开发
    Git Gui、Ssh key的使用和ideaui配置使用Git解决冲突(下)
    Git和Github的介绍、简单操作、冲突(上)
    Shiro身份认证、盐加密
    Shiro简介、入门案例、web容器的集成
    SpringMVC入门
    Mybatis之关联关系(一对多、多对多)
    Mybatis整合(Redis、Ehcache)实现二级缓存
  • 原文地址:https://www.cnblogs.com/freewater/p/2299893.html
Copyright © 2011-2022 走看看