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;
}
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 name="license_content">用戶協議 \n \n一、服務條款的確認和接納 \n...</string>
注意:字串資源中的換行必須自行寫 \n,原本 txt 檔裡的換行不會被保留。
這樣做會把漢字截斷,導致 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 讓它自己管理未完成的多位元序列。
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();
InputStream is = getAssets().open("test.txt");
用法與 raw 幾乎相同,只是取得方式不同。
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;
}
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 中自動關流,避免例外時洩漏檔案描述符。