本文展示一套雙模式數據緩存方案:優先使用外部存儲(SD 卡),不可用時回退至 SharedPreferences。適用於文本數據的持久化緩存。
/**
* 緩存文本數據
* @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();
}
}
/**
* 獲取緩存的文本信息
* @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;
}
mkdirs() 確保多級目錄存在擴展建議:可進一步封裝為泛型緩存管理器,支持對象序列化(Gson/JSON)、緩存過期時間、LRU 淘汰策略等高級功能。