首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

Android 數據緩存實戰:SharedPreferences 與文件存儲雙模式

     編輯:Java 綜合教學

緩存策略概覽

本文展示一套雙模式數據緩存方案:優先使用外部存儲(SD 卡),不可用時回退至 SharedPreferences。適用於文本數據的持久化緩存。

核心工具類實現

1. 存儲字符串數據

/**
 * 緩存文本數據
 * @param context 上下文
 * @param key 鍵
 * @param value 值
 */
public static void putString(Context context, String key, String value) {
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        try {
            // 用 MD5 編碼 key 作為文件名,避免特殊字符問題
            String fileName = MD5Encoder.encode(key);
            File file = new File(Environment.getExternalStorageDirectory() + "/beijingnews/files", fileName);
            File parentFile = file.getParentFile();
            
            // 確保目錄存在
            if (!parentFile.exists()) parentFile.mkdirs();
            if (!file.exists()) file.createNewFile();
            
            // 寫入文件
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(value.getBytes());
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
            LogUtil.e("文本數據緩存失敗");
        }
    } else {
        // 回退到 SharedPreferences
        SharedPreferences sp = context.getSharedPreferences("atguigu", Context.MODE_PRIVATE);
        sp.edit().putString(key, value).commit();
    }
}

2. 讀取緩存字符串

/**
 * 獲取緩存的文本信息
 * @param context 上下文
 * @param key 鍵
 * @return 緩存值,失敗返回空串
 */
public static String getString(Context context, String key) {
    String result = "";
    
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        try {
            String fileName = MD5Encoder.encode(key);
            File file = new File(Environment.getExternalStorageDirectory() + "/beijingnews/files", fileName);
            
            if (file.exists()) {
                FileInputStream is = new FileInputStream(file);
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int length;
                while ((length = is.read(buffer)) != -1) {
                    stream.write(buffer, 0, length);
                }
                is.close();
                stream.close();
                result = stream.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
            LogUtil.e("文本數據讀取失敗");
        }
    } else {
        SharedPreferences sp = context.getSharedPreferences("atguigu", Context.MODE_PRIVATE);
        result = sp.getString(key, "");
    }
    return result;
}

關鍵設計要點

  • 雙模式降級:SD 卡可用時用文件存儲(適合大數據),不可用時自動切換到 SharedPreferences
  • 文件名 MD5 編碼:避免 key 包含非法字符導致文件創建失敗
  • 目錄自動創建:mkdirs() 確保多級目錄存在
  • 流資源管理:讀寫後正確關閉流,防止洩漏
  • 異常捕獲:所有 I/O 操作包裹在 try-catch 中,保證應用不崩潰

適用場景

  • 新聞客戶端緩存文章內容、圖片 URL 列表
  • 離線數據預加載
  • 用戶偏好設置備份
  • 臨時數據持久化

擴展建議:可進一步封裝為泛型緩存管理器,支持對象序列化(Gson/JSON)、緩存過期時間、LRU 淘汰策略等高級功能。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved