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

Android 讀取中文檔案的編碼處理與檔案讀寫整理

一、如何顯示 assets/license.txt(中文)的內容

方法一:available() 取得位元組數後一次讀完

private String readUserAgreementFromAsset(String assetName) {
    String content = "";
    try {
        InputStream is = getAssets().open(assetName);
        if (is != null) {
            DataInputStream dIs = new DataInputStream(is);
            int length = dIs.available();
            byte[] buffer = new byte[length];
            dIs.read(buffer);
            content = EncodingUtils.getString(buffer, "UTF-8");
            is.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return content;
}

方法二:BufferedReader 逐行讀取後拼接

A. 先逐行讀取,再整體轉碼 UTF-8:

BufferedReader d = new BufferedReader(new InputStreamReader(is));
while (d.ready()) {
    sb.append(d.readLine() + "\n");
}
content = EncodingUtils.getString(sb.toString().getBytes(), "UTF-8");

B. 直接在 InputStreamReader 指定 UTF-8,讀完即為正確字串(推薦):

BufferedReader d = new BufferedReader(new InputStreamReader(is, "UTF-8"));
while (d.ready()) {
    sb.append(d.readLine() + "\n");
}
content = sb.toString();

另外,new String(buffer, "utf-8") 也能完成同樣的轉碼。

替代方法三:把內容放進 string.xml

<string name="license_content">用戶協議
\n \n一、服務條款的確認和接納
\n...</string>

注意:字串資源中的換行必須自行寫 \n,原本 txt 檔裡的換行不會被保留。

不可取的方法四:每次讀 4096 位元組分別轉碼

這樣做會把漢字截斷,導致 4096 的倍數附近出現亂碼:

byte[] buffer = new byte[1024 * 4];
int length = 0;
while ((length = dIs.read(buffer)) > 0) {
    content = EncodingUtils.getString(buffer, 0, length, "UTF-8");
    sb.append(content);   // 邊界處的多位元字元會被切開
}

這正是「編碼必須在完整位元組序列上進行」的經典反例。要串流處理,應使用 InputStreamReader 讓它自己管理未完成的多位元序列。

二、Android 中的檔案讀寫

(1) 讀取 res/raw(唯讀)

InputStream in = getResources().openRawResource(R.raw.test);
int length = in.available();
byte[] buffer = new byte[length];
in.read(buffer);
String res = EncodingUtils.getString(buffer, "UTF-8");  // 選對編碼否則亂碼
in.close();

(2) 讀取 assets(唯讀)

InputStream is = getAssets().open("test.txt");

用法與 raw 幾乎相同,只是取得方式不同。

(3) 私有目錄 /data/data/包名/files/

public void writeFileData(String fileName, String message) {
    try {
        FileOutputStream fout = openFileOutput(fileName, MODE_PRIVATE);
        fout.write(message.getBytes());
        fout.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public String readFileData(String fileName) {
    String str = "";
    try {
        FileInputStream fin = openFileInput(fileName);
        int length = fin.available();
        byte[] bytes = new byte[length];
        fin.read(bytes);
        str = EncodingUtils.getString(bytes, "UTF-8");
        fin.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return str;
}

(4) sdcard 目錄 /mnt/sdcard/

public void writeFile2Sdcard(String fileName, String message) {
    try {
        FileOutputStream fout = new FileOutputStream(fileName);
        fout.write(message.getBytes());
        fout.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public String readFileFromSdcard(String fileName) {
    String res = "";
    try {
        FileInputStream fin = new FileInputStream(fileName);
        int length = fin.available();
        byte[] buffer = new byte[length];
        fin.read(buffer);
        res = EncodingUtils.getString(buffer, "UTF-8");
        fin.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return res;
}

寫入 sdcard 別忘了在 manifest 加上 READ_EXTERNAL_STORAGE/WRITE_EXTERNAL_STORAGE 權限,Android 6.0 以後還需執行期動態請求。另外,範例中大量使用 available() 決定緩衝大小並一次讀完,這對小型文字檔沒問題,但正式專案建議改用 BufferedReader 或 Kotlin 的 readText(),並在 try-with-resources 中自動關流,避免例外時洩漏檔案描述符。

Copyright © Linux教程網 All Rights Reserved