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

Android 讀寫應用私有文件夾中的數據

編輯:Android 程式設計入門

本文介紹如何將數據存儲到應用的私有文件夾並讀寫。

打開應用文件夾的 I/O 方法

Context 提供了兩個方法,用於打開應用文件夾的 I/O(文件不存在時會創建):

FileInputStream openFileInputStream(String fileName);
FileOutputStream openFileOutputStream(String fileName, int mode);

其中 mode 的取值:

  • MODE_APPEND:追加方式存儲。
  • MODE_PRIVATE:私有方式存儲,其他應用無法訪問。
  • MODE_WORLD_READABLE:當前文件可被其他應用讀取。
  • MODE_WORLD_WRITEABLE:當前文件可被其他應用寫入。

訪問應用文件夾的方法

Context 還提供了以下方法:

  • File getFilesDir():獲取文件夾的絕對路徑。
  • String[] fileList():獲取文件夾下的所有文件。
  • deleteFile(String fileName):刪除文件夾下的指定文件。

實例

public class NewActivity extends AppCompatActivity {
    private static final String FileName = "FirstSharedPreference";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        try {
            FileOutputStream fos = openFileOutput(FileName, MODE_WORLD_WRITEABLE);
            String str = "I am good at Android";
            byte[] bytes = str.getBytes();
            fos.write(bytes, 0, bytes.length);

            FileInputStream fis = openFileInput(FileName);
            InputStreamReader isr = new InputStreamReader(fis);
            BufferedReader br = new BufferedReader(isr);
            String data = "";
            StringBuilder sb = new StringBuilder();
            while ((data = br.readLine()) != null) {
                sb.append(data);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

透過 openFileOutput 寫入數據、openFileInput 讀取數據,即可輕鬆完成應用私有文件夾內文件的讀寫操作。

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