編輯:關於 Android 程式設計
很多人以為 Android 的 I/O 就是 Java SE 那一套,這是個常見誤解。兩者確有共通之處,但差異更多——Android 檔案的存放位置不同,讀取方式自然也不一樣。以下按四種典型場景分別說明。
assets 中的檔案只能讀、不能寫:
public static void readFromAsset(Context context, String fileName) {
try {
InputStream in = context.getResources().getAssets().open(fileName);
int length = in.available();
byte[] buffer = new byte[length];
in.read(buffer);
in.close();
String content = new String(buffer, "UTF-8");
ToastUtils.showShortToast(context, content);
} catch (IOException e) {
e.printStackTrace();
}
}
同樣是唯讀:
public static void readFromRaw(Context context, int rawResId) {
InputStream in = context.getResources().openRawResource(rawResId);
try {
int length = in.available();
byte[] buffer = new byte[length];
in.read(buffer);
String res = EncodingUtils.getString(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
可能有人會問:為什麼不用 Java 7 的 try-with-resources(try (InputStream in = ...))自動關流?因為那需要 Java SE 1.7 以後的語法支援,當時的 Android 版本還不支援,只能老實寫 finally。
先讀:
public static void readFromPackage(Context context, String fileName) {
try {
FileInputStream fis = context.openFileInput(fileName);
int length = fis.available();
byte[] buffer = new byte[length];
fis.read(buffer);
String content = new String(buffer, "UTF-8");
ToastUtils.showLongToast(context, content);
} catch (IOException ex) {
ex.printStackTrace();
}
}
再寫。權限模式建議用 Context.MODE_PRIVATE,否則容易踩到安全性紅線。可用的模式有:
public static void writeToPackage(Context context, String fileName, String str) {
try {
FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
byte[] buffer = str.getBytes();
fos.write(buffer);
fos.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
需要在 Manifest 中宣告權限:
<!-- 寫入資料到 SD 卡 --> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <!-- 建立或刪除 SD 卡中的檔案 --> <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
讀取:
public void readFromSdcard(Context context, String fileName) {
try {
FileInputStream fis = new FileInputStream(fileName);
int length = fis.available();
byte[] buffer = new byte[length];
fis.read(buffer);
String content = new String(buffer, "UTF-8");
ToastUtils.showLongToast(context, content);
} catch (IOException ex) {
ex.printStackTrace();
}
}
寫入:
public static void writeToSdCardFile(byte[] buffer, Context context, String fileName) {
try {
FileOutputStream fos = new FileOutputStream(fileName);
fos.write(buffer);
fos.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
上面都是最基礎的示範。真實專案裡,取得串流之後通常還要再包一層緩衝(BufferedInputStream/BufferedOutputStream/BufferedReader),效能差異在讀寫大檔時非常明顯,強烈建議不要直接用裸串流。
另外有兩點值得注意。第一,available() 回傳的是「不阻塞情況下可讀取的估計位元組數」,並不等於檔案總大小,用它來配置 buffer 只在小型檔案上勉強可靠;嚴謹的做法是迴圈讀到 EOF。第二,Android 4.4 之後,可寫的外部儲存位置轉為 Environment.getExternalStorageDirectory() 與 app-specific 目錄(getExternalFilesDir()),加上後續版本的儲存權限模型收緊,寫入共用位置的行為已大不如前寬鬆。新專案若只是存放應用自己的資料,優先考慮內部儲存或 getExternalFilesDir(),可以省掉一堆權限與相容性問題。
自定義控件三部曲之繪圖篇(十二):Paint 之 setXfermode(三)
前面兩篇講完了 setXfermode 的 SRC 系列模式,還剩 DST 系列沒說。這一篇把 DST 相關模式講透,並用幾個完整實例把它們用起來。 一、DST 系列模
OpenCV for Android 人臉識別入門:從相冊選圖到框選臉部
在 Android 上做人臉識別,OpenCV 是常見的選擇。透過 Java API,開發者可以較快完成環境建置與基本流程,例如從相冊選圖、轉換成 OpenCV 可用的
[Android] 一次搞懂 Activity 的四種啟動模式
Android 為 Activity 提供了四種啟動模式:standard、singleTop、singleTask 與 singleInstance。開發時只要在 A
RecyclerView 多種 Item 布局加載實作
RecyclerView 要實現多種 Item 布局,關鍵在於 Adapter 的 getItemViewType() 與 onCreateViewHolder()。開發