Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 讀取 assets 內本機 JSON 檔並解決中文亂碼

編輯:關於 Android 程式設計

把預設資料以 JSON 檔放進 assets 資料夾,是 Android 常見的做法——省去首次啟動的網路請求,也能讓 App 在離線狀態下正常運作。但很多人會遇到同一個問題:檔案明明沒錯,讀出來的中文卻是一片亂碼。原因幾乎都在字元編碼。

寫法一:常見但會亂碼的版本

public static String readLocalJson(Context context, String fileName) {
    String jsonString = "";
    String resultString = "";
    try {
        BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(context.getResources().getAssets().open(fileName)));
        while ((jsonString = bufferedReader.readLine()) != null) {
            resultString += jsonString;
        }
    } catch (Exception e) {
        // TODO: handle exception
    }
    return resultString;
}

問題出在 InputStreamReader 沒有指定編碼。此時它會使用平台的預設編碼,而這個預設值在不同裝置、不同 Android 版本上並不一致。當你的 JSON 檔是 UTF-8 存檔,而裝置預設卻是 GBK 或其他編碼時,中文就會解成亂碼。

順帶一提,用 resultString += jsonString 在迴圈中反覆拼接字串,每次都會產生新的 String 物件,資料量大時會造成不必要的記憶體配置。改用 StringBuilder 是更好的習慣。

寫法二:明確指定編碼,中文正常顯示

public static String readLocalJson(Context context, String fileName) {
    String jsonString = "";
    String resultString = "";
    try {
        InputStream inputStream = context.getResources().getAssets().open(fileName);
        byte[] buffer = new byte[inputStream.available()];
        inputStream.read(buffer);
        resultString = new String(buffer, "GB2312");
    } catch (Exception e) {
        // TODO: handle exception
    }
    return resultString;
}

這裡的做法是一次把整個檔案讀進 byte 陣列,再用指定的編碼還原成字串。前提是你的文字檔存檔時要與程式碼中的編碼一致——範例中搭配的是「UTF-8 / UNIX 換行」的存檔設定,程式碼側則解成 GB2312,兩者必須對得上,否則一樣會亂碼。

另外提醒,inputStream.available() 回傳的是「目前可讀取的估計位元組數」,對 assets 中的本地檔案通常等於檔案大小,但這並不是 API 保證的行為。正式專案中建議改用 ByteArrayOutputStream 逐段讀取,會更保險。

更穩妥的寫法:直接把編碼寫死

綜合上述,這是我會推薦的版本——固定使用 UTF-8,並用 StringBuilder 與 try-with-resources 確保資源釋放:

public static String readLocalJson(Context context, String fileName) {
    StringBuilder sb = new StringBuilder();
    try (InputStream is = context.getResources().getAssets().open(fileName);
         BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"))) {
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
    } catch (IOException e) {
        Log.e("readLocalJson", "讀取 " + fileName + " 失敗", e);
    }
    return sb.toString();
}

注意 try-with-resources 需要 minSdkVersion 19 以上,或搭配 Android Gradle 插件的 desugaring 支援。

亂碼排查三步驟

  1. 確認檔案本身的編碼。用編輯器(VS Code、Notepad++)檢視並顯示文件末尾的編碼標示。存檔時請統一選「UTF-8」。若檔案帶有 BOM,某些解析器會在第一個 key 前面多出三個隱形字元,導致 JSONObject 解析失敗。
  2. 確認讀取端編碼與檔案一致。把 new String(buffer, "UTF-8") 或 InputStreamReader(is, "UTF-8") 明確寫出來,不要依賴預設值。
  3. 印出原始位元組做驗證。在讀取後用 Log.d() 印出前幾個 byte 的十六進位值。UTF-8 的中文通常是 3 個位元組一組且首 byte 落在 0xE0~0xEF 之間,若看到的是 0xEF 0xBB 0xBF,那就是 BOM。

結論很簡單:檔案存 UTF-8,程式碼讀 UTF-8,兩邊對齊就不會亂碼。範例中的 GB2312 是為了示範「明確指定編碼」這個觀念,新專案請一律採用 UTF-8。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved