編輯:初階開發
檔案讀寫是很日常的需求,與其每次重寫一遍,不如包成一個輔助類。以下這個 FileIOHelper 就是這樣誕生的,往後直接拿去用即可。
public class FileIOHelper {
Context context;
File file;
FileInputStream fin;
FileOutputStream fout;
public FileIOHelper(Context c, String name, String path) throws IOException {
context = c;
file = new File(path, name);
file.createNewFile();
fin = new FileInputStream(file);
fout = new FileOutputStream(file);
}
}
建構子接收 Context、檔名與路徑,確保檔案存在後,同時開啟輸入與輸出串流。
public void write(String s) throws IOException {
fout.write(s.getBytes());
fout.close();
}
public byte[] read(int s, int l) throws IOException {
byte[] save = new byte[l];
fin.read(save, s, l);
return save;
}
public String encode(byte[] array) {
return EncodingUtils.getString(array, TEXT_ENCODING);
}
public int length() {
return (int) file.length();
}
public class FileIOUsage extends Activity {
public final static String NAME = "griffinshi.txt";
public final static String PATH = "data/data/com.android.FileIO";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
FileIOHelper helper = new FileIOHelper(this, NAME, PATH);
String string = "Hello to Gryphone!";
helper.write(string);
byte[] array = helper.read(0, helper.length());
String data = helper.encode(array);
TextView tv = new TextView(this);
tv.setText(data);
setContentView(tv);
} catch (IOException e) {
e.printStackTrace();
}
}
}
執行後畫面上會顯示剛剛寫入的內容,形成一個最簡單的「寫入再讀回」驗證。
不支援追加。原實作每次都用 new FileOutputStream(file) 開檔,這會把原內容整個清空,因此只能整份覆寫。若需要追加,建構 FileOutputStream 時要傳第二個參數 true:new FileOutputStream(file, true)。
串流同時開著。建構子裡把 fin 與 fout 一起開啟,實際上大部分情境只需要其中一個。而且寫入後關掉 fout、讀取後也該關掉 fin,否則檔案會被佔用。
沒有 flush。寫入後直接 close 通常沒問題,但若中途需要讀回同一份內容,務必先 flush() 再讀,否則可能讀到舊資料。
路徑寫死。範例把路徑硬編碼成 data/data/com.android.FileIO,這在真机上很可能因權限而失敗。正確做法是用 getFilesDir() 取得應用私有目錄,例如:
File file = new File(context.getFilesDir(), "griffinshi.txt");
這樣路徑會自動指向 /data/data/<你的套件名>/files,不必也不能自行猜測。
read 的返回值未檢查。fin.read(save, s, l) 實際讀到的位元組數可能小於 l(尤其讀到檔尾時),應該用回傳值來決定有效長度,否則 byte 陣列尾端會是一堆 0。
建議改用 try-with-resources。Java 7 之後可以這樣寫,自動關閉串流並把例外處理收斂乾淨:
try (FileInputStream in = new FileInputStream(file)) {
byte[] data = in.readAllBytes();
return new String(data, StandardCharsets.UTF_8);
}
用 adb 進 shell 查看:
$ adb shell # cd data # cd com.android.FileIO # ls griffinshi.txt lib

看到 griffinshi.txt 出現在清單中,就代表寫入成功。若要在自己的電腦上直接看內容,可以 adb pull 把檔案拉回本機;不過新版 Android 對 /data/data 的存取已大幅收緊,非 root 環境下通常需要用 run-as 套件名 才能進入應用私有目錄。
讓 Android 應用相容多種螢幕解析度
Android 裝置解析度差異大,常見包含 QVGA、HVGA、WVGA、FWVGA 等。若圖片資源未針對不同解析度設計,可能出現拉伸或顯示異常。Resource 目錄可
與 Nexus One 重逢:Android 2.2 的第一手體驗
Nexus One 對我來說算是頗有緣分的一支手機。還記得 1 月 12 日晚上寫下它的評測,因為對這支機器實在關注,後來在轉換工作環境的過渡期裡,也正好是它一路陪著我。
關於 Android 中 sdcard 讀寫的常見錯誤與排查
剛接觸 Android 開發時,往 sdcard 推送文件經常會失敗。本文整理幾種典型的錯誤訊息與對應的解法。 典型錯誤訊息 [2011-05-04 08:45:33]
Android 採用 PULL 解析 XML 文件
為何選擇 PULL 在 Android 中解析 XML 時,PULL 是相當受歡迎的方案。與 SAX 相比,PULL 會回傳整數事件,讓開發者能依序掌握文件起點、標籤起訖