Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 技術基礎

第60章、把資料寫進記憶卡再讀回來(從零開始學Android)

編輯:Android 技術基礎

以檔案方式保存資料是最傳統、也最容易理解的做法。好消息是:Android 上的檔案讀寫寫法與 Java SE 的 I/O 幾乎完全一致,File、FileOutputStream、FileInputStream、PrintStream、Scanner 這些老朋友都能直接沿用,差別只在「檔案要放哪裡」以及「記得申請權限」。

一、兩種儲存位置的差別

Android 的內部儲存空間屬於 App 私有,路徑可由 getFilesDir() 取得,不需要任何權限,但容量有限、卸載 App 時會一併清除。外部儲存卡(可移除或模擬的共用空間)則要用 Environment.getExternalStorageDirectory() 取得根路徑,空間大、可用檔案總管看見,但必須先確認已掛載並申請讀寫權限。本章示範的是後者。

二、設計介面

開啟 res/layout/activity_main.xml,放一個垂直 LinearLayout,內含兩顆按鈕:

  • Button,id 為 save,文字「保存數據(File)」。
  • Button,id 為 read,文字「讀取數據(File)」。

三、程式主體 MainActivity.java

開啟 src/com.genwoxue.file/MainActivity.java,先宣告兩顆按鈕、一個 File 物件,以及檔名常數 data.txt。寫入與讀取的處理分別放在兩個 OnClickListener 裡。

1. 寫入檔案

PrintStream ps = null;
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
    Toast.makeText(getApplicationContext(), "讀取失敗,SD存儲卡不存在!",
                   Toast.LENGTH_LONG).show();
    return;
}
String path = Environment.getExternalStorageDirectory().toString()
            + File.separator + "genwoxue"
            + File.separator + FILENAME;
file = new File(path);
if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
try {
    ps = new PrintStream(new FileOutputStream(file));
    ps.println("跟我學網址:www.genwoxue.com");
    ps.println("電子郵件:hello@genwoxue.com");
} catch (FileNotFoundException e){
    e.printStackTrace();
} finally {
    ps.close();
}

寫入的關鍵在最後三行。new FileOutputStream(file) 是位元組層的輸出,包一層 PrintStream 之後就能直接用 println() 寫文字並自動換行,省去自己處理編碼與緩衝的麻煩。finally 區塊中關流是必要的,否則資料可能還停在緩衝區裡沒真正落盤。

2. 讀取檔案

StringBuffer info = new StringBuffer();
// ... 同樣先判斷儲存卡與檔案是否存在 ...
Scanner scan = new Scanner(new FileInputStream(file));
while (scan.hasNext()){
    info.append(scan.next()).append("☆☆☆\n");
}
Toast.makeText(getApplicationContext(), info.toString(),
               Toast.LENGTH_LONG).show();

讀取時先用 file.exists() 確認檔案在不在,不存在就提示「文件不存在!」並返回,避免抛出 FileNotFoundException。範例用 Scanner 以空白作為分隔逐段讀取,因此輸出的每段文字之間會被插入「☆☆☆」。如果你想一次讀一整行而不是以空白切開,改用 BufferedReader 搭配 readLine() 會更合適。

注意:範例為求簡潔,把 ps.close() 與 scan.close() 直接寫在 finally 中。實務上建議改用 try-with-resources,即使中途抛出例外也能確保資源釋放。

四、設定檔與權限

開啟 AndroidManifest.xml,在 uses-sdk 之後補上兩項權限:android.permission.READ_EXTERNAL_STORAGE 與 android.permission.WRITE_EXTERNAL_STORAGE。少了這兩行,程式在寫檔時會直接抛出 Permission Denial。activity 段落維持標準寫法,記得保留 MAIN 與 LAUNCHER 的 intent-filter。

注意:Android 6.0(API 23)以後,這兩項權限屬於執行期危險權限,必須在操作前用 requestPermissions() 向使用者取得同意;Android 11 以後若要存取任意共用目錄,還需改用 Environment.isExternalStorageManager() 搭配特殊權限,或改用 Storage Access Framework。

五、運行結果

先按「保存」建立 genwoxue 資料夾並寫入 data.txt,再按「讀取」就能看到刚寫入的兩行內容。若把檔案拉出來用記事本開啟,會看到一般純文字檔的樣子——這正是檔案式儲存最迷人的地方:資料是人看得懂、拿得走的。

六、實務上的建議

檔案儲存適合少量、結構鬆散的資料,例如日誌、快取或匯出檔。若資料有明確欄位、需要查詢與排序,請改用 SQLite;若只是幾個設定值,SharedPreferences 會更省事。另外別忘了在寫入過程中處理例外,並避免在主執行緒寫入大檔案,以免造成畫面卡頓。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved