Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 以文件(File)形式保存與讀取數據的方法

編輯:關於 Android 程式設計

除了 SharedPreferences,Android 還支持直接以文件的形式把數據保存到設備中。這種方式通過 Context 提供的 openFileInput 和 openFileOutput 方法,分別獲得標準的 FileInputStream 和 FileOutputStream,操作起來直觀又方便。本文就來演示如何寫入與讀取。

一、寫數據到文件

用 openFileOutput 打開(或創建)目標文件,把字符串轉成字節寫入即可。文件會被保存到 /data/data/包名/files/ 目錄下:

findViewById(R.id.file).setOnClickListener(v -> {
    try {
        // 以追加模式打開 huangbiao.txt
        FileOutputStream fos = openFileOutput("huangbiao.txt", Context.MODE_APPEND);
        fos.write("huangbiao".getBytes());
        fos.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
});

二、讀取數據

讀取時用 openFileInput 得到輸入流,先根據可用字節數申請緩衝區,再把內容讀進來轉成字符串:

findViewById(R.id.read_file).setOnClickListener(v -> {
    try {
        FileInputStream fis = openFileInput("huangbiao.txt");
        // available() 返回估算的可用字節數
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        String aaa = new String(buffer);
        System.out.println(aaa);
        fis.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
});

這種方式的核心就在 openFileOutput 與 openFileInput 這對方法上,它們幫我們屏蔽了底層的文件路徑拼接細節,直接以文件名操作應用私有空間裡的文件。對於需要保存稍大一些、又不便放入 SharedPreferences 的數據(例如簡單的文本記錄、緩存內容),以 File 形式存儲是一個不錯的選擇。實際使用時,記得養成用完即關流的好習慣,並做好異常處理。

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