用 java 将文件的编码从GBK 转换成 UTF8收藏

private static void transferFile(String srcFileName, String destFileName) throws IOException {
   String line_separator = System.getProperty("line.separator");
   FileInputStream fis = new FileInputStream(srcFileName);
   StringBuffer content = new StringBuffer();
   DataInputStream in = new DataInputStream(fis);
   BufferedReader d = new BufferedReader(new InputStreamReader(in, "GBK"));// , "UTF-8"
   String line = null;
   while ((line = d.readLine()) != null)
    content.append(line + line_separator);
   d.close();
   in.close();
   fis.close();
     
   Writer ow = new OutputStreamWriter(new FileOutputStream(destFileName), "utf-8");
   ow.write(content.toString());
   ow.close();
}

将一个GBK编码的文件转成UTF8 编码的文件,有兴趣的话,你可以试下

不知道为什么, 用 ultraEdit 以二进制查看生成的文件时,文件头部并没有以 EF BB BF 开头,但是以 windows 记事本打开后,另存为,可以发现其为 utf8 的. 我的 eclipse 的工作区的编码是 utf-8的,转换前,打开A.java 是乱码,转换后就可以正常显示了.
如果你觉得有什么问题,可以联系我,一起讨论下.....

//参考了 字符,字节和编码 http://www.regexlab.com/zh/encoding.htm

posted on 2009-02-10 14:18  dhj  阅读(579)  评论(0编辑  收藏  举报

导航