編輯:關於 Android 程式設計
檔案讀寫是基礎但反覆用到的能力。這裡整理四個實用的方法:讀取媒體檔的位元組串流、讀取文字檔、寫入位元組、寫入文字。
讀取圖片、影片等二進位檔案時,用 ByteArrayOutputStream 承接串流內容,最後一次轉為陣列。
public static byte[] readStream(String imagepath) throws Exception {
FileInputStream fs = new FileInputStream(imagepath);
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while (-1 != (len = fs.read(buffer))) {
outStream.write(buffer, 0, len);
}
outStream.close();
fs.close();
return outStream.toByteArray();
}
這個寫法有個實務問題:整個檔案都被載入記憶體。讀取大型媒體檔時極易 OOM。若後續用途是顯示圖片,應改用 BitmapFactory.decodeFile() 搭配 inSampleSize 降採樣;若用途是上傳,則應直接串流處理,不必先落地成 byte[]。
public String readFile(String filename) {
String content = null;
File file = new File(filename);
try {
FileReader reader = new FileReader(file);
char[] chars = new char[(int) file.length()];
reader.read(chars);
content = new String(chars);
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
return content;
}
這裡有個隱患:file.length() 回傳的是位元組數,而 char 陣列需要的是字元數。若檔案含中文等多位元組編碼,兩者不相等,會導致讀取結果被截斷或尾部出現亂碼。穩妥的寫法是用 StringBuilder 迴圈讀取:
public String readFile(String filename) {
StringBuilder sb = new StringBuilder();
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(
new FileInputStream(filename), "UTF-8"));
String line;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try { reader.close(); } catch (IOException e) { /* ignore */ }
}
}
return sb.toString();
}
明確指定編碼也很重要。FileReader 會使用平台預設編碼,在不同裝置上可能不一致。
public void writeFile(String filePath, byte[] f) {
try {
FileOutputStream out = new FileOutputStream(new File(filePath));
out.write(f);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
寫 log 或純文字內容時用這個版本:
public void writeFile(String filePath, String f) {
FileWriter fw = null;
try {
fw = new FileWriter(filePath);
fw.write(f);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fw != null) {
try { fw.close(); } catch (IOException e) { /* ignore */ }
}
}
}
一律用 finally 或 try-with-resources 關檔。上面四個範例原本的寫法在異常發生時不會關閉串流,長時間運行會耗盡檔案描述符。若專案的 minSdk 已達 19 以上,直接用 try-with-resources 最乾淨:
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
// ...
}
外部儲存需要權限與存在性檢查。寫入 SD 卡前應先確認掛載狀態:
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
// 外部儲存不可用,走降級方案
}
同時在 manifest 中加入 WRITE_EXTERNAL_STORAGE;Android 6.0 之後還需要 runtime permission 申請流程。
寫檔前確保父目錄存在。new FileOutputStream() 遇到不存在的路徑會拋 FileNotFoundException,而這個例外訊息同時涵蓋「路徑不存在」與「無權限」兩種情況,排查時容易誤判。事先呼叫 file.getParentFile().mkdirs() 可省下不少時間。
寫檔的原子性。若檔案內容不容許寫到一半就中斷(例如設定檔),建議先寫入暫存檔,成功後再用 renameTo() 覆蓋目標檔。這樣即使中途斷電或進程被殺,原檔案仍然完整。
為移植到 Android 平台的 Cocos2d-x 專案加入 XML 佈局檔(圖文)
把 Cocos2d-x 專案移植到 Android 之後,常會需要在其 Activity 上疊加原生控制項,這時候就得靠 XML 佈局檔。以下記錄完整流程。 一、新增佈局
Android 手機無法連接 Mac 的解決方式:adb_usb.ini 設定
問題現象部分 Android 手機在連接 Mac 時,可能無法被 adb 或 DDMS 正確辨識。有些裝置即使開啟 USB 偵錯,仍然看不到裝置。這類問題通常與 Vend
從零打造 FlowLayout:自訂 ViewGroup 實作流式版面
本文整理自鴻洋的 FlowLayout 系列文章,並加入自己的實作與驗證。 一、什麼是 FlowLayout 所謂流式版面,就是控制項依據 ViewGroup 的寬度自動
Android RSA 加解密完整實作(含 OpenSSL 金鑰產生與 Base64)
概述 RSA 是目前最具影響力的非對稱加密演算法,其安全性建立在單純的數論事實上:兩個大質數相乘非常容易,但要把乘積因式分解回原來的質數卻極其困難。因此我們可以把乘積公開