Android JSON 文件缓存

思路

采用文件形式存储JSON数据。将网络请求出的JSON数据,解析成String,然后使用字符流读、写。

公司项目中以前使用的是ObjectInputStreamObjectOutputStream这样的对象字节流来读、写,效率较字符流比 —— 较低

将JSON-String 缓存到文件

首先获取Android上可用的缓存目录;之后,字符流写入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public static void writeJson(Context c, String json, String fileName) {
File cacheRoot = TextUtils.equals(Environment.getExternalStorageState(), (Environment.MEDIA_MOUNTED)) ? c.getExternalCacheDir() : c.getCacheDir();
BufferedWriter writer = null;
try {
File file = new File(cacheRoot, fileName);
writer = new BufferedWriter(new FileWriter(file));
writer.write(json);
writer.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
IOUtil.close(writer);
}
}

读取JSON-String 缓存文件

字符流读取

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
public static StringBuilder readJson(Context c, String fileName) {
return readJson(c, fileName, 24 * 3600 * 1000L);//指定缓存1天将过期
}
/**
* @param expireTime 缓存过期的时间毫秒值
*/
public static StringBuilder readJson(Context c, String fileName, long expireTime) {
File cacheRoot = TextUtils.equals(Environment.getExternalStorageState(), (Environment.MEDIA_MOUNTED)) ? c.getExternalCacheDir() : c.getCacheDir();
StringBuilder builder = new StringBuilder();
BufferedReader reader = null;
try {
File file = new File(cacheRoot, fileName);
if (!isValid(file, expireTime)) return builder;
reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
IOUtil.close(reader);
}
return builder;
}
/**
* 验证文件是否有效
* @param f
* @param timeout
* @return true: 表示有效
*/
private static boolean isValid(File f, long timeout) {
if (f == null || !f.exists()) return false;
if (timeout <= 0) return true;
if (System.currentTimeMillis() - f.lastModified() > timeout) {//已过期
f.deleteOnExit();
return false;
}
return true;
}
------ 本文结束 ------

版权声明
协议:No Fuck License

stone 创作并维护
本文首发于 stone世界 博客( http://stone86.top
版权所有,侵权必究。如要转载,请声明出处

Fork me on GitHub