編輯:關於 Android 程式設計
想把一份小型設定檔、初始資料或 HTML 模板跟著 APK 一起打包,assets/ 是最方便的位置。它和 res/raw/ 最大的差別是:assets 底下的檔案不會被壓縮、也不會自動產生 R 資源 id,必须用檔案名稱當作字串去開啟。代價是靈活,好處是可以放任意副檔名、任意層級的目錄結構。
讀取流程一律是:getAssets().open("檔名") 拿到 InputStream,再自行決定要用字元流還是位元組流讀。以下示範兩種常見寫法。
適合純文字、需要按行處理的內容(例如設定檔、CSV)。用 InputStreamReader 把位元組流轉成字元流,再包一層 BufferedReader,就能享受 readLine() 的便利。
public String getFromAssets(String fileName) {
BufferedReader reader = null;
StringBuilder result = new StringBuilder();
try {
InputStreamReader inputReader =
new InputStreamReader(getResources().getAssets().open(fileName));
reader = new BufferedReader(inputReader);
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return result.toString();
}
相較於直接把字串用 += 接起來,這裡改用 StringBuilder。Java 的字串是不可變的,每次 += 都會產生一個新物件並複製舊內容,行數一多就是不必要的效能浪費。
適合檔案不大、你想一次拿到全部內容的情況,例如讀一份 JSON 或 XML 字串。
// 從 assets 資料夾讀取檔案內容並轉為字串
public String getFromAssets(String fileName) {
String result = "";
InputStream in = null;
try {
in = getResources().getAssets().open(fileName);
// 取得檔案的位元組數
int length = in.available();
// 建立對應大小的 byte 陣列
byte[] buffer = new byte[length];
// 把檔案內容讀進 byte 陣列
in.read(buffer);
result = new String(buffer, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return result;
}
這裡有兩個細節值得留意。第一,原範例使用了 EncodingUtils.getString(),這個 class 在較新的 Android SDK 中已被移除,改用 new String(buffer, "UTF-8") 才是安全且明確的做法。第二,available() 回傳的是「目前不阻塞就能讀到的估計位元組數」,對 assets 裡的本地檔案通常等於完整大小,但它在 API 契約上並非保證值;若要更嚴謹,應該用迴圈反覆 read 直到讀滿,或直接改用 ByteArrayOutputStream 串流複製。
如果你不想依賴 available(),可以讓串流類自己處理緩衝:
public String getFromAssets(String fileName) {
InputStream in = null;
try {
in = getResources().getAssets().open(fileName);
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int count;
while ((count = in.read(buffer)) != -1) {
out.write(buffer, 0, count);
}
return out.toString("UTF-8");
} catch (Exception e) {
e.printStackTrace();
return "";
} finally {
if (in != null) {
try {
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
assets/config/db.json,就要傳 "config/db.json",assets 沒有 R 資源可用。getFilesDir() 或外部儲存空間再操作。finally 收尾;若你的專案 minSdk 已達 API 19 以上,也可以直接用 try-with-resources 讓語法更簡潔。
Android 重力感測器在遊戲開發中的應用
Android 重力感測器在遊戲開發中的應用 手勢操作是智慧型手機的一大魅力,而感測器則讓遊戲能感知裝置的空間姿態。感測器是能探測光、熱、溫度、重力、方向等的裝置,And
Android 自訂 View 控制項
自訂 View 概念自訂 View 可避免在 XML 中重複撰寫相同版面。以下以左右兩個 TextView 的列表項目為例。準備版面配置建立 item_list_cus_
Android 實現批量照片上傳:拍照、相冊選擇與伺服器傳輸
需求背景在許多企業級 Android 應用中,批量上傳照片是常見需求,例如證件、門店照片、業務簽核資料等。本文整理從相機拍照、相冊選擇、圖片壓縮到批量上傳伺服器的完整思路
微信理財通安全嗎?登入、支付與贖回風險解析
微信理財通的安全性與手機短信、支付密碼綁定有關。登入密碼可能透過短信重置,因此手機要設鎖屏密碼。 支付密碼通常需要銀行卡、身分證與手機等資料,破解難度較高。贖回資金主要只