zoukankan      html  css  js  c++  java
  • 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     }
  • 相关阅读:
    使用 RestSharp 调用 WebAPI 接口
    Android Studio 下载安装目录
    多线程之await/async
    ScriptX进行Web打印
    Sqlserver 查询最新修改过的表、过程和视图等
    SqlServer中的bit类型
    .Net 6
    PDA 使用总结
    SQL Server 发布订阅 发布类型详解
    Profile对象
  • 原文地址:https://www.cnblogs.com/lude313/p/4796970.html
Copyright © 2011-2022 走看看