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

Android 讀取中文文字檔與檔案讀寫常見做法

編輯:關於 Android 程式設計

中文亂碼的原因

讀取中文文字檔時,若編碼不正確,可能會出現亂碼。常見做法是明確指定 UTF-8,並避免在切割位元組時把中文字元截斷。

讀取 assets 中的文字檔

assets 下的檔案只能讀取,不能直接寫入。以下使用 BufferedReader 逐行讀取。

InputStream is = getAssets().open("license.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));

StringBuilder sb = new StringBuilder();
String line;

while ((line = reader.readLine()) != null) {
    sb.append(line).append('\n');
}

is.close();
String content = sb.toString();

讀取 raw 資源

res/raw 下的資源也只能讀取,可透過 openRawResource 開啟。

InputStream in = getResources().openRawResource(R.raw.test);
int length = in.available();
byte[] buffer = new byte[length];
in.read(buffer);
String res = new String(buffer, "UTF-8");
in.close();

讀寫私有檔案

應用程式私有檔案位於 /data/data/套件名稱/files 下,可用 openFileOutput 與 openFileInput 操作。

String fileName = "test.txt";
String message = "測試內容";

FileOutputStream fout = openFileOutput(fileName, MODE_PRIVATE);
fout.write(message.getBytes("UTF-8"));
fout.close();
FileInputStream fin = openFileInput(fileName);
int length = fin.available();
byte[] bytes = new byte[length];
fin.read(bytes);
String text = new String(bytes, "UTF-8");
fin.close();

讀寫 SD 卡檔案

若需要存取 /mnt/sdcard 下的檔案,可直接使用 FileInputStream 與 FileOutputStream。

FileOutputStream fout = new FileOutputStream(fileName);
fout.write(message.getBytes("UTF-8"));
fout.close();
FileInputStream fin = new FileInputStream(fileName);
int length = fin.available();
byte[] buffer = new byte[length];
fin.read(buffer);
String res = new String(buffer, "UTF-8");
fin.close();

注意事項

若需要讀取大型檔案,不建議一次全部載入記憶體。若使用固定大小緩衝區,也要注意 UTF-8 中文字元可能被切斷,造成亂碼。

小結

Android 檔案讀寫的關鍵在於選擇正確的串流與編碼。assets 與 raw 適合唯讀資源,私有檔案適合應用內部資料,SD 卡則適合較大或需對外分享檔案。

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