今天我们来学习一下用JSON数据缓存在本地
现在开始贴代码
public class Cache_Json {
/**
*
* @param json 字符串
* @param index 保存的第几个标记
*/
private void SaveLocal(String json,int index){
BufferedWriter bw = null;
try {
File dir = FileUtils.getCacheDir();//设定缓存目录(这里自己设定)
File file = new File(dir,"flag_"+index);
FileWriter fw = new FileWriter(file);
bw = new BufferedWriter(fw);
bw.write(System.currentTimeMillis()+1000*100+"");//记录保存时间
bw.newLine();//换行
bw.write(json);//把整行json文件保存起来
bw.flush();
bw.close();
}catch (Exception e){
e.printStackTrace();
}
}
/**
*
* @param index 获取缓存的json
* @return
*/
private String getCache_Json(int index ){
// 如果发现文件已经过期了 就不要再去复用缓存了
File dir=FileUtils.getCacheDir();// 获取缓存所在的文件夹
File file = new File(dir, "home_" + index);
try {
FileReader fr=new FileReader(file);
BufferedReader br=new BufferedReader(fr);
long outOfDate = Long.parseLong(br.readLine()); //读取缓存记录的时间
if(System.currentTimeMillis()>outOfDate)
{ // 如果发现文件已经过期了 就不要再去复用缓存了
return null;
}
else
{
String str=null;
StringWriter sw=new StringWriter();
while((str=br.readLine())!=null){
sw.write(str);
}
return sw.toString();
}
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}
}
小小的工具类结束