Android 文件的存储和加载

Android 文件的存储和加载,主要用于请求网络中json文件的缓存,引入了一个简单的过期时间,供大家参考学习!

文件存储

 1 private void saveLocal(String json, int index) {
 2         
 3         BufferedWriter bw = null;
 4         try {
 5             File dir=FileUtils.getCacheDir();
 6             //在第一行写一个过期时间 
 7             File file = new File(dir, getKey()+"_" + index); // /mnt/sdcard/googlePlay/cache/home_0
 8             FileWriter fw = new FileWriter(file);
 9              bw = new BufferedWriter(fw);
10             bw.write(System.currentTimeMillis() + 1000 * 100 + "");
11             bw.newLine();// 换行
12             bw.write(json);// 把整个json文件保存起来
13             bw.flush();
14             bw.close();
15         } catch (Exception e) {
16             e.printStackTrace();
17         }finally{
18             IOUtils.closeQuietly(bw);
19         }
20     }

文件加载

 1 private String loadLocal(int index) {
 2         //  如果发现文件已经过期了 就不要再去复用缓存了
 3         File dir=FileUtils.getCacheDir();// 获取缓存所在的文件夹
 4         File file = new File(dir, getKey()+"_" + index); 
 5         try {
 6             FileReader fr=new FileReader(file);
 7             BufferedReader br=new BufferedReader(fr);
 8             long outOfDate = Long.parseLong(br.readLine());
 9             if(System.currentTimeMillis()>outOfDate){
10                 return null;
11             }else{
12                 String str=null;
13                 StringWriter sw=new StringWriter();
14                 while((str=br.readLine())!=null){
15                 
16                     sw.write(str);
17                 }
18                 return sw.toString();
19             }
20             
21         } catch (Exception e) {
22             e.printStackTrace();
23             return null;
24         }
25     }
原文地址:https://www.cnblogs.com/lude313/p/4796970.html