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

安卓應用中的文件讀寫操作全解析

編輯:關於 Android 程式設計

在 Android 開發裡,文件的讀寫是最基礎也最常見的需求之一。本文整理了從權限申請、路徑獲取到讀寫、緩存與刪除的一系列常用操作,幫助你快速掌握核心要點。

一、申請存儲權限

在訪問外部存儲之前,必須先在清單文件中聲明相應權限:


    
    ...

需要注意的是,WRITE_EXTERNAL_STORAGE 已經隱含了讀取權限,因此只需申請寫入權限即可同時具備讀取能力。

二、獲取當前應用的私有目錄

若要在應用私有空間中定位文件,可以借助 getFilesDir():

File file = new File(context.getFilesDir(), filename);

三、寫入文件

使用 openFileOutput 即可將字符串寫入文件:

String filename = myfile;
String string = "Hello world!";
FileOutputStream outputStream;
try {
    outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
    outputStream.write(string.getBytes());
    outputStream.close();
} catch (Exception e) {
    e.printStackTrace();
}

四、生成緩存文件

借助 File.createTempFile 可以在緩存目錄中創建臨時文件:

public File getTempFile(Context context, String url) {
    File file;
    try {
        String fileName = Uri.parse(url).getLastPathSegment();
        file = File.createTempFile(fileName, null, context.getCacheDir());
    } catch (IOException e) {
        // 創建文件時發生錯誤
    }
    return file;
}

五、判斷 SD 卡是否可用

在讀寫外部存儲前,最好先檢測其狀態:

/* SD卡是否可寫 */
public boolean isExternalStorageWritable() {
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        return true;
    }
    return false;
}

/* SD卡是否可讀 */
public boolean isExternalStorageReadable() {
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state) ||
        Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
        return true;
    }
    return false;
}

六、創建文件

如果希望創建一個公共文件,即使應用被卸載後文件依然保留:

public File getAlbumStorageDir(String albumName) {
    // Environment.DIRECTORY_PICTURES 為系統常量,代表圖片文件夾
    File file = new File(Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES), albumName);
    if (!file.mkdirs()) {
        Log.e(LOG_TAG, "Directory not created");
    }
    return file;
}

如果希望文件隨應用卸載而被一併刪除,則應使用應用專屬目錄:

public File getAlbumStorageDir(Context context, String albumName) {
    // 若沒有合適的子目錄,可傳遞 null 給 getExternalFilesDir(),
    // 這將返回外部存儲上該應用專用目錄的根目錄
    File file = new File(context.getExternalFilesDir(
            Environment.DIRECTORY_PICTURES), albumName);
    if (!file.mkdirs()) {
        Log.e(LOG_TAG, "Directory not created");
    }
    return file;
}

諸如 DIRECTORY_PICTURES 這類 API 常量提供的目錄名稱至關重要,它們能確保系統正確處理文件。例如,存放在 DIRECTORY_RINGTONES 中的文件會被系統媒體掃描器識別為鈴聲,而非音樂。

七、刪除文件

最直接的方式是調用文件對象的 delete() 方法:

myFile.delete();

如果文件保存在內部存儲中,也可以通過 Context 調用 deleteFile() 來定位並刪除:

myContext.deleteFile(fileName);
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved