文件缓存类把文件放到缓存上

// 从缓存读取数据

String vehicleData = FileCache.Get("vdata_"+cityId, 5);//5分钟失效

// 保存到缓存

FileCache.Set("vdata_"+cityId, m);



package net.joystart.common.util; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileWriter; import java.io.UnsupportedEncodingException; import java.text.DateFormat; import java.util.Date; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import net.joystart.common.util.date.DateSerializer; import net.joystart.vehicle.service.impl.VehicleLock; /*** * 文件缓存类 * * @author lidongchun@bagechuxing.cn */ public class FileCache { private static String cachePath = ConfigUtil.pro.get("cachePath") .toString(); // 获取缓存文件内容 public static String Get(String key, int ttl) { try { String fileName = cachePath + "/" + key; String encoding = "UTF-8"; File file = new File(fileName); long from = file.lastModified(); long to = new Date().getTime(); int minutes = (int) ((to - from) / 1000); if (minutes > ttl) { return null; } Long filelength = file.length(); byte[] filecontent = new byte[filelength.intValue()]; FileInputStream in = new FileInputStream(file); in.read(filecontent); in.close(); return new String(filecontent, encoding); } catch (Exception e) { e.printStackTrace(); } return null; } // 设置缓存文件内容 public static boolean Set(String key, Object content) { VehicleLock lock = new VehicleLock(key); if (content instanceof String == false) { GsonBuilder gb = new GsonBuilder(); gb.registerTypeAdapter(java.util.Date.class, new DateSerializer()).setDateFormat(DateFormat.LONG); Gson gson = gb.create(); content = gson.toJson(content); } final String fileContent = String.valueOf(content); lock.wrap(new Runnable() { @Override public void run() { try { String pathname = cachePath + "/" + key; BufferedWriter out = new BufferedWriter(new FileWriter( pathname)); out.write(fileContent); out.close(); } catch (IOException e) { } } }); return true; } }

 

转载于:https://www.cnblogs.com/cuijinlong/p/8341721.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值