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

Android 內部儲存與外部儲存完全解析

編輯:關於 Android 程式設計

先想一個問題:打開手機設定,進入應用管理,選任一 App,你會看到「清除快取」與「清除資料」兩個按鈕。點擊清除快取時刪掉的是哪裡的資料?清除資料又是刪掉哪裡的資料?讀完本文你會有答案。

Android 開發中經常聽到「記憶體」、「內部儲存」、「外部儲存」三個概念,很多人常把它們搞混。英文裡其實不會混淆:記憶體是 memory,內部儲存是 Internal Storage,外部儲存是 External Storage;但翻譯成中文後前兩者都被簡稱為「記憶體」,於是就亂了。

要分辨它們,最直觀的方式是打開 DDMS 的 File Explorer,裡面有三個資料夾值得注意:data、mnt、storage。

一、內部儲存

data 資料夾就是我們常說的內部儲存(未 root 的手機無法開啟)。裡面有兩個重點資料夾:

  • data/app:存放所有已安裝 App 的 apk 檔。我們在除錯時可以看到 console 輸出 Uploading ...,就是把 apk 上傳到這個資料夾,上傳成功後才開始安裝。
  • data/data/包名/:每個 App 的私有目錄,裡面通常有這幾個子目錄:
    • shared_prefs:使用 SharedPreferences 持久化的 XML 檔就存在這裡
    • databases:App 的資料庫檔
    • files:一般資料檔
    • cache:快取檔

存在這裡的檔案統稱為內部儲存。

二、外部儲存

外部儲存才是我們日常操作最多的區域,一般是 storage 資料夾(部分機型可能表現在 mnt 下,各家實作略有差異)。

在 storage 中通常有個 sdcard 資料夾,裡面的檔案分兩類:

  • 公有目錄:系統為我們建立的九大類,例如 DCIM、DOWNLOAD、MUSIC、PICTURES 等,所有 App 都能存取。
  • 私有目錄:名為 Android 的資料夾,其下有 data 資料夾,裡面按包名建立子目錄,對應各 App 專用的外部儲存空間。

三、操作儲存空間

一般來說我們不會也不該直接操作內部儲存——沒有 root 權限根本無法存取,實際上內部儲存主要由系統維護(程式碼中仍可透過 Context 的 API 訪問)。由於內部空間有限,開發中我們多半操作外部儲存。

Google 官方建議:App 的資料應存放在外部儲存的私有目錄(即該 App 的包名目錄下)。這樣使用者卸載 App 時,相關資料會一併刪除。若你直接在 /storage/sdcard 底下自建一個資料夾,卸載 App 時該資料夾不會被清掉,容易招致使用者反感。

路徑的兩種分類方式

若依路徑特徵區分,可分為兩類:

  • 路徑中含有包名:與某個 App 相關,透過 Context 的方法取得。
  • 路徑中不含包名:與特定 App 無關,透過 Environment 的方法取得。
// 內部儲存
context.getFilesDir();          // data/data/包名/files
context.getCacheDir();          // data/data/包名/cache

// 外部儲存私有目錄
context.getExternalFilesDir();  // /storage/sdcard/Android/data/包名/files
context.getExternalCacheDir();  // /storage/sdcard/Android/data/包名/cache

// 外部儲存公有目錄
Environment.getExternalStorageDirectory();                  // 根目錄
Environment.getExternalStoragePublicDirectory(type);        // 指定類型目錄

其中 getExternalFilesDir() 與 getExternalStoragePublicDirectory() 都需要傳入一個字串參數,用來指定要存取哪個子目錄,參數值採用 Environment 提供的常量。來看看它的原始碼註解:

/**
 * @param type The type of files directory to return. May be null for
 * the root of the files directory, or one of the following Environment
 * constants for a subdirectory:
 *      Environment.DIRECTORY_MUSIC,
 *      Environment.DIRECTORY_PODCASTS,
 *      Environment.DIRECTORY_RINGTONES,
 *      Environment.DIRECTORY_ALARMS,
 *      Environment.DIRECTORY_NOTIFICATIONS,
 *      Environment.DIRECTORY_PICTURES,
 *      Environment.DIRECTORY_MOVIES
 *
 * @return The path of the directory holding application files on
 * external storage. Returns null if external storage is not currently
 * mounted so it could not ensure the path exists.
 */
@Nullable
public abstract File getExternalFilesDir(@Nullable String type);

可以看到我們能存取 files 目錄下的 Music、Movies、Pictures 等多種子目錄。

小結:開發中不建議往內部儲存寫入過多資料,畢竟空間有限;使用外部儲存時最好把檔案放在私有目錄下,這既方便系統維護,也能避免使用者反感。

回到最初的問題

點擊「清除資料」時,刪掉的是內部儲存中對應的 files 與 cache 資料夾內容,以及外部儲存中對應的 files 與 cache 資料夾內容。而「清除快取」只會刪掉 cache 部分,files 中的資料會保留下來。

附錄:檔案操作工具類

public class SDCardHelper {

    // 判斷 SD 卡是否掛載
    public static boolean isSDCardMounted() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }

    // 取得 SD 卡根目錄
    public static String getSDCardBaseDir() {
        if (isSDCardMounted()) {
            return Environment.getExternalStorageDirectory().getAbsolutePath();
        }
        return null;
    }

    // 取得 SD 卡總空間大小(MB)
    public static long getSDCardSize() {
        if (isSDCardMounted()) {
            StatFs fs = new StatFs(getSDCardBaseDir());
            return fs.getBlockCountLong() * fs.getBlockSizeLong() / 1024 / 1024;
        }
        return 0;
    }

    // 取得 SD 卡剩餘空間大小(MB)
    public static long getSDCardFreeSize() {
        if (isSDCardMounted()) {
            StatFs fs = new StatFs(getSDCardBaseDir());
            return fs.getFreeBlocksLong() * fs.getBlockSizeLong() / 1024 / 1024;
        }
        return 0;
    }

    // 取得 SD 卡可用空間大小(MB)
    public static long getSDCardAvailableSize() {
        if (isSDCardMounted()) {
            StatFs fs = new StatFs(getSDCardBaseDir());
            return fs.getAvailableBlocksLong() * fs.getBlockSizeLong() / 1024 / 1024;
        }
        return 0;
    }

    // 存到 SD 卡公有目錄
    public static boolean saveFileToSDCardPublicDir(byte[] data, String type, String fileName) {
        if (!isSDCardMounted()) {
            return false;
        }
        BufferedOutputStream bos = null;
        try {
            File file = Environment.getExternalStoragePublicDirectory(type);
            bos = new BufferedOutputStream(new FileOutputStream(new File(file, fileName)));
            bos.write(data);
            bos.flush();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeQuietly(bos);
        }
        return false;
    }

    // 存到 SD 卡自訂目錄
    public static boolean saveFileToSDCardCustomDir(byte[] data, String dir, String fileName) {
        if (!isSDCardMounted()) {
            return false;
        }
        BufferedOutputStream bos = null;
        try {
            File file = new File(getSDCardBaseDir() + File.separator + dir);
            if (!file.exists()) {
                file.mkdirs();  // 遞迴建立自訂目錄
            }
            bos = new BufferedOutputStream(new FileOutputStream(new File(file, fileName)));
            bos.write(data);
            bos.flush();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeQuietly(bos);
        }
        return false;
    }

    // 存到 SD 卡私有 Files 目錄
    public static boolean saveFileToSDCardPrivateFilesDir(byte[] data, String type,
                                                          String fileName, Context context) {
        if (!isSDCardMounted()) {
            return false;
        }
        BufferedOutputStream bos = null;
        try {
            File file = context.getExternalFilesDir(type);
            bos = new BufferedOutputStream(new FileOutputStream(new File(file, fileName)));
            bos.write(data);
            bos.flush();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeQuietly(bos);
        }
        return false;
    }

    // 存到 SD 卡私有 Cache 目錄
    public static boolean saveFileToSDCardPrivateCacheDir(byte[] data, String fileName,
                                                          Context context) {
        if (!isSDCardMounted()) {
            return false;
        }
        BufferedOutputStream bos = null;
        try {
            File file = context.getExternalCacheDir();
            bos = new BufferedOutputStream(new FileOutputStream(new File(file, fileName)));
            bos.write(data);
            bos.flush();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeQuietly(bos);
        }
        return false;
    }

    // 把 Bitmap 存到 SD 卡私有 Cache 目錄
    public static boolean saveBitmapToSDCardPrivateCacheDir(Bitmap bitmap, String fileName,
                                                           Context context) {
        if (!isSDCardMounted()) {
            return false;
        }
        BufferedOutputStream bos = null;
        try {
            File file = context.getExternalCacheDir();
            bos = new BufferedOutputStream(new FileOutputStream(new File(file, fileName)));
            if (fileName != null
                    && (fileName.contains(".png") || fileName.contains(".PNG"))) {
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);
            } else {
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            }
            bos.flush();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeQuietly(bos);
        }
        return false;
    }

    // 從 SD 卡讀取檔案
    public static byte[] loadFileFromSDCard(String fileDir) {
        BufferedInputStream bis = null;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            bis = new BufferedInputStream(new FileInputStream(new File(fileDir)));
            byte[] buffer = new byte[8 * 1024];
            int c;
            while ((c = bis.read(buffer)) != -1) {
                baos.write(buffer, 0, c);
                baos.flush();
            }
            return baos.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                baos.close();
                if (bis != null) {
                    bis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    // 從 SD 卡讀取並解碼為 Bitmap
    public static Bitmap loadBitmapFromSDCard(String filePath) {
        byte[] data = loadFileFromSDCard(filePath);
        if (data != null) {
            return BitmapFactory.decodeByteArray(data, 0, data.length);
        }
        return null;
    }

    // 取得 SD 卡公有目錄路徑
    public static String getSDCardPublicDir(String type) {
        return Environment.getExternalStoragePublicDirectory(type).toString();
    }

    // 取得 SD 卡私有 Cache 目錄路徑
    public static String getSDCardPrivateCacheDir(Context context) {
        return context.getExternalCacheDir().getAbsolutePath();
    }

    // 取得 SD 卡私有 Files 目錄路徑
    public static String getSDCardPrivateFilesDir(Context context, String type) {
        return context.getExternalFilesDir(type).getAbsolutePath();
    }

    // 判斷檔案是否存在
    public static boolean isFileExist(String filePath) {
        return new File(filePath).isFile();
    }

    // 從 SD 卡刪除檔案
    public static boolean removeFileFromSDCard(String filePath) {
        File file = new File(filePath);
        if (file.exists()) {
            return file.delete();
        }
        return false;
    }

    private static void closeQuietly(Closeable closeable) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved