Java文件编码自动转换工具类(只改变编码,不会改变文件内容)

  本篇随笔主要介绍了一个用java语言写的将一个文件编码转换为另一个编码并不改变文件内容的工具类:

    通过读取源文件内容,用URLEncoding重新编码解码的方式实现。

     

    

 1 public class ChangeFileEncoding {
 2     public static int fileCount = 0;
 3     public static String sourceFileRoot = "替换为要转换的源文件或源目录"; // 将要转换文件所在的根目录
 4     public static String sourceCharset = "GB2312"; // 源文件编码
 5     public static String targetCharset = "utf8"; // 目标文件编码
 6     public static void main(String[] args) throws IOException {
 7         File fileDir = new File(sourceFileRoot);
 8         convert(fileDir);
 9         System.out.println("Total Dealed : " + fileCount + "Files");
10     }
11 
12     public static void convert(File file) throws IOException {
13         // 如果是文件则进行编码转换,写入覆盖原文件
14         if (file.isFile()) {
15             // 只处理.java结尾的代码文件
16             if (file.getPath().indexOf(".java") == -1) {
17                 return;
18             }
19             InputStreamReader isr = new InputStreamReader(new FileInputStream(
20                     file), sourceCharset);
21             BufferedReader br = new BufferedReader(isr);
22             StringBuffer sb = new StringBuffer();
23             String line = null;
24             while ((line = br.readLine()) != null) {
25                 // 注意写入换行符
26                 line =  URLEncoder.encode(line, "utf8");
27                 sb.append(line + "\r\n");//windows 平台下 换行符为 \r\n
28             }
29             br.close();
30             isr.close();
31 
32             File targetFile = new File(file.getPath());
33             OutputStreamWriter osw = new OutputStreamWriter(
34                     new FileOutputStream(targetFile), targetCharset);
35             BufferedWriter bw = new BufferedWriter(osw);
36             // 以字符串的形式一次性写入
37             bw.write(URLDecoder.decode(sb.toString(), "utf8"));
38             bw.close();
39             osw.close();
40 
41             System.out.println("Deal:" + file.getPath());
42             fileCount++;
43         } else {
44             //利用递归对目录下的每个以.java结尾的文件进行编码转换
45             for (File subFile : file.listFiles()) {
46                 convert(subFile);
47             }
48         }
49     }
50 
51 }

 

    

原文地址:https://www.cnblogs.com/Michaelwjw/p/5929425.html