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

Android 資料持久化工具類合集:外部儲存、內部儲存、Assets 與 SharedPreferences

編輯:關於 Android 程式設計

開發中資料持久化是繞不開的一環。除了可以直接搭配 ORM 使用的 SQLite,Android 還提供了檔案 I/O 與 SharedPreferences 等方式。以下整理四個可直接複用的工具類。

一、外部儲存卡工具類

需要權限:android.permission.WRITE_EXTERNAL_STORAGE、android.permission.MOUNT_UNMOUNT_FILESYSTEMS。

package cn.edu.zafu.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import android.os.Environment;

/**
 * 外部儲存卡工具類
 *
 * @author lizhangqu
 * @version 1.0
 */
public class ExternalStorageUtil {

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

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

    /** 取得外部儲存卡根路徑 */
    public static String getExternalStoragePath() {
        if (isExternalStorageWritable()) {
            return Environment.getExternalStorageDirectory().getAbsolutePath();
        } else {
            return null;
        }
    }

    /** 取得下載目錄路徑 */
    public static String getExternalDownloadPath() {
        return Environment
                .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                .getAbsolutePath();
    }

    /** 向根路徑寫入字串 */
    public static boolean write(String fileName, String content) {
        return write("/", fileName, content);
    }

    /** 向根路徑寫入位元組 */
    public static boolean writeBytes(String fileName, byte[] bytes) {
        return writeBytes("/", fileName, bytes);
    }

    /** 向指定目錄寫入字串,path 以 / 開頭結尾 */
    public static boolean write(String path, String fileName, String content) {
        return writeBytes(path, fileName, content.getBytes());
    }

    /** 向指定目錄寫入位元組陣列 */
    public static boolean writeBytes(String path, String fileName, byte bytes[]) {
        boolean flag = false;
        if (!path.equals("/")) {
            File dir = new File(getExternalStoragePath() + path);
            if (!dir.exists()) {
                if (!(dir.mkdir() || dir.isDirectory())) {
                    // 目錄建立失敗或不是目錄
                    return false;
                }
            }
        }
        File file = new File(getExternalStoragePath() + path + fileName);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file, false);
            fos.write(bytes);
            flag = true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return flag;
    }

    /** 從根路徑讀位元組 */
    public static byte[] readBytes(String fileName) {
        return readBytes("/", fileName);
    }

    /** 從指定目錄讀位元組 */
    public static byte[] readBytes(String path, String fileName) {
        File file = new File(getExternalStoragePath() + path + fileName);
        if (!file.isFile()) {
            return null;
        } else {
            FileInputStream fis = null;
            try {
                fis = new FileInputStream(file);
                int length = fis.available();
                byte[] buffer = new byte[length];
                fis.read(buffer);
                return buffer;
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return null;
        }
    }

    /** 從根目錄讀文字 */
    public static String read(String fileName) {
        return read("/", fileName);
    }

    /** 從指定目錄讀文字 */
    public static String read(String path, String fileName) {
        try {
            byte[] readBytes = readBytes(path, fileName);
            if (readBytes == null) {
                return null;
            }
            return new String(readBytes, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /** 從根目錄刪除 */
    public static boolean delete(String fileName) {
        return delete("/", fileName);
    }

    /** 從指定目錄刪除 */
    public static boolean delete(String path, String fileName) {
        File file = new File(getExternalStoragePath() + path + fileName);
        if (file.exists()) {
            return file.delete();
        } else {
            return true;
        }
    }
}

二、內部儲存工具類

package cn.edu.zafu.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import android.content.Context;

/**
 * 內部儲存卡工具類
 *
 * @author lizhangqu
 * @version 1.0
 */
public class InternalStorageUtil {

    /** 在原檔案後追加內容 */
    public static boolean append(Context context, String fileName, String content) {
        return writeBytes(context, fileName, content.getBytes(), true);
    }

    /** 寫入檔案,存在則覆蓋 */
    public static boolean write(Context context, String fileName, String content) {
        return writeBytes(context, fileName, content.getBytes(), false);
    }

    /** 寫入位元組 */
    public static boolean writeBytes(Context context, String fileName, byte[] content) {
        return writeBytes(context, fileName, content, false);
    }

    /** 依 isAppend 決定覆蓋或追加 */
    public static boolean writeBytes(Context context, String fileName, byte[] content,
                                     boolean isAppend) {
        FileOutputStream fout = null;
        boolean flag = false;
        try {
            if (isAppend) {
                fout = context.openFileOutput(fileName, Context.MODE_APPEND);
            } else {
                fout = context.openFileOutput(fileName, Context.MODE_PRIVATE);
            }
            fout.write(content);
            flag = true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fout != null) {
                    fout.close();
                    fout = null;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return flag;
    }

    /** 讀取檔案 */
    public static String read(Context context, String fileName) {
        byte[] buffer = readBytes(context, fileName);
        String result = null;
        try {
            result = new String(buffer, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }

    /** 讀取檔案為位元組陣列 */
    public static byte[] readBytes(Context context, String fileName) {
        FileInputStream fin = null;
        byte[] buffer = null;
        try {
            fin = context.openFileInput(fileName);
            int length = fin.available();
            buffer = new byte[length];
            fin.read(buffer);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fin != null) {
                    fin.close();
                    fin = null;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return buffer;
    }

    /** 清除所有檔案,任一失敗則回傳 false */
    public static boolean clear(Context context) {
        boolean flag = true;
        String[] files = context.fileList();
        for (String fileName : files) {
            boolean result = context.deleteFile(fileName);
            if (result == false) {
                flag = false;
            }
        }
        return flag;
    }

    /** 依檔名刪除檔案 */
    public static boolean delete(Context context, String fileName) {
        return context.deleteFile(fileName);
    }

    /** 回傳內部儲存的絕對路徑 */
    public static String getFileDir(Context context) {
        File filesDir = context.getFilesDir();
        return filesDir.getAbsolutePath();
    }
}

三、資源檔案讀取工具類

package cn.edu.zafu.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import android.content.Context;

/**
 * assets 資源的讀取
 *
 * @author lizhangqu
 * @version 1.0
 */
public class ResouceFileUtil {

    /** 從 assets 讀取文字 */
    public static String readStringFromAssert(Context context, String fileName) {
        String result = null;
        byte[] buffer = readBytesFromAssert(context, fileName);
        try {
            result = new String(buffer, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }

    /** 從 raw 讀取文字 */
    public static String readStringFromRaw(Context context, int rawId) {
        String result = null;
        byte[] buffer = readBytesFromRaw(context, rawId);
        try {
            result = new String(buffer, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }

    /** 從 assets 讀取檔案為位元組陣列 */
    public static byte[] readBytesFromAssert(Context context, String fileName) {
        InputStream is = null;
        byte[] buffer = null;
        try {
            is = context.getAssets().open(fileName);
            int size = is.available();
            buffer = new byte[size];
            is.read(buffer);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                    is = null;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return buffer;
    }

    /** 從 raw 讀取檔案為位元組陣列 */
    public static byte[] readBytesFromRaw(Context context, int rawId) {
        InputStream is = null;
        byte[] buffer = null;
        try {
            is = context.getResources().openRawResource(rawId);
            int size = is.available();
            buffer = new byte[size];
            is.read(buffer);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                    is = null;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return buffer;
    }
}

四、SharedPreferences 操作工具類

package cn.edu.zafu.utils;

import android.content.Context;
import android.content.SharedPreferences;

/**
 * SharedPreference 方式持久化資料的工具類
 *
 * @author lizhangqu
 * @version 1.0
 */
public class SharedPreferenceUtil {

    /** 保存鍵值對 */
    public static boolean set(Context context, String fileName, String key, String value) {
        SharedPreferences sharedPreferences = context.getSharedPreferences(
                fileName, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(key, value);
        return editor.commit();
    }

    /** 取得鍵對應的值,沒有則回傳空字串 */
    public static String get(Context context, String fileName, String key) {
        return get(context, fileName, key, "");
    }

    /** 取得鍵對應的值,沒有則回傳 defaultValue */
    public static String get(Context context, String fileName, String key, String defaultValue) {
        SharedPreferences sharedPreferences = context.getSharedPreferences(
                fileName, Context.MODE_PRIVATE);
        return sharedPreferences.getString(key, defaultValue);
    }

    /** 移除一項 */
    public static boolean remove(Context context, String fileName, String key) {
        SharedPreferences sharedPreferences = context.getSharedPreferences(
                fileName, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.remove(key);
        return editor.commit();
    }

    /** 清除檔案內容 */
    public static boolean clear(Context context, String fileName) {
        SharedPreferences sharedPreferences = context.getSharedPreferences(
                fileName, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.clear();
        return editor.commit();
    }

    /** 判斷某一項是否存在 */
    public static boolean contatins(Context context, String fileName, String key) {
        SharedPreferences sharedPreferences = context.getSharedPreferences(
                fileName, Context.MODE_PRIVATE);
        return sharedPreferences.contains(key);
    }
}

怎麼選

內部儲存(getFilesDir())不對外暴露,適合存放私有資料,容量受限於 App 的可用空間;外部儲存適合放較大的檔案或需要與其他應用共享的內容,但從 Android 10 起受 Scoped Storage 規範,建議改用 getExternalFilesDir();assets 與 raw 都是唯讀的隨包資源,raw 支援 openRawResourceFd() 可直接餵給 MediaPlayer,較大的媒體檔放 raw 更方便;SharedPreferences 則適合設定值等小型鍵值資料,資料量大時應改用資料庫。另外範例中的 commit() 是同步寫入,若在主執行緒頻繁呼叫會卡 UI,可替換為 apply()。

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