使用缓存问题

Java代码   收藏代码
  1. public class CacheManager {  
  2.   
  3.     private static final long MAX_SIZE = 5242880L; // 5MB  
  4.   
  5.     private CacheManager() {  
  6.   
  7.     }  
  8.   
  9.     public static void cacheData(Context context, byte[] data, String name) throws IOException {  
  10.   
  11.         File cacheDir = context.getCacheDir();  
  12.         long size = getDirSize(cacheDir);  
  13.         long newSize = data.length + size;  
  14.   
  15.         if (newSize > MAX_SIZE) {  
  16.             cleanDir(cacheDir, newSize - MAX_SIZE);  
  17.         }  
  18.   
  19.         File file = new File(cacheDir, name);  
  20.         FileOutputStream os = new FileOutputStream(file);  
  21.         try {  
  22.             os.write(data);  
  23.         }  
  24.         finally {  
  25.             os.flush();  
  26.             os.close();  
  27.         }  
  28.     }  
  29.   
  30.     public static byte[] retrieveData(Context context, String name) throws IOException {  
  31.   
  32.         File cacheDir = context.getCacheDir();  
  33.         File file = new File(cacheDir, name);  
  34.   
  35.         if (!file.exists()) {  
  36.             // Data doesn't exist  
  37.             return null;  
  38.         }  
  39.   
  40.         byte[] data = new byte[(int) file.length()];  
  41.         FileInputStream is = new FileInputStream(file);  
  42.         try {  
  43.             is.read(data);  
  44.         }  
  45.         finally {  
  46.             is.close();  
  47.         }  
  48.   
  49.         return data;  
  50.     }  
  51.   
  52.     private static void cleanDir(File dir, long bytes) {  
  53.   
  54.         long bytesDeleted = 0;  
  55.         File[] files = dir.listFiles();  
  56.   
  57.         for (File file : files) {  
  58.             bytesDeleted += file.length();  
  59.             file.delete();  
  60.   
  61.             if (bytesDeleted >= bytes) {  
  62.                 break;  
  63.             }  
  64.         }  
  65.     }  
  66.   
  67.     private static long getDirSize(File dir) {  
  68.   
  69.         long size = 0;  
  70.         File[] files = dir.listFiles();  
  71.   
  72.         for (File file : files) {  
  73.             if (file.isFile()) {  
  74.                 size += file.length();  
  75.             }  
  76.         }  
  77.   
  78.         return size;  
  79.     }  
  80. }  
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值