本篇隨筆主要介紹了一個用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 }