Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Java 文件編碼批量轉換工具類實作

老專案從 GB2312 遷到 UTF-8,往往要面對成百上千個源檔案。手改不現實,於是有了這支小工具:傳入一個檔案或目錄,它就自動把編碼轉換並覆寫原檔,同時保持文件內容不變。

實作思路並不玄妙:以源編碼讀入每一行,用 URLEncoder 編碼、再用 URLDecoder 解碼,藉此完成字元集的中轉,最後以目標編碼寫回。

public class ChangeFileEncoding {
    public static int fileCount = 0;
    public static String sourceFileRoot = "替換為要轉換的源文件或源目錄";
    public static String sourceCharset = "GB2312";  // 源編碼
    public static String targetCharset = "utf8";    // 目標編碼

    public static void main(String[] args) throws IOException {
        File fileDir = new File(sourceFileRoot);
        convert(fileDir);
        System.out.println("Total Dealed : " + fileCount + " Files");
    }

    public static void convert(File file) throws IOException {
        // 若是檔案則進行編碼轉換,寫入時覆蓋原檔
        if (file.isFile()) {
            // 只處理 .java 結尾的程式碼檔案
            if (file.getPath().indexOf(".java") == -1) {
                return;
            }
            InputStreamReader isr = new InputStreamReader(
                    new FileInputStream(file), sourceCharset);
            BufferedReader br = new BufferedReader(isr);
            StringBuffer sb = new StringBuffer();
            String line = null;
            while ((line = br.readLine()) != null) {
                // 注意補回換行符
                line = URLEncoder.encode(line, "utf8");
                sb.append(line + "\r\n"); // Windows 平台換行符為 \r\n
            }
            br.close();
            isr.close();

            File targetFile = new File(file.getPath());
            OutputStreamWriter osw = new OutputStreamWriter(
                    new FileOutputStream(targetFile), targetCharset);
            BufferedWriter bw = new BufferedWriter(osw);
            // 以字串形式一次性寫入
            bw.write(URLDecoder.decode(sb.toString(), "utf8"));
            bw.close();
            osw.close();

            System.out.println("Deal:" + file.getPath());
            fileCount++;
        } else {
            // 利用遞迴處理目錄下每個 .java 檔案
            for (File subFile : file.listFiles()) {
                convert(subFile);
            }
        }
    }
}

幾個實務提醒:遞迴是處理多層目錄的關鍵;覆寫原檔前最好先備份或提交一次版本庫,畢竟轉碼是不可逆操作;若只想改單一檔案,把過濾條件放寬即可;另外 URLEncoder 這一中轉方式對中文表現良好,但遇到特殊符號仍建議抽查幾個檔案確認結果。

Copyright © Linux教程網 All Rights Reserved