Android缓存之磁盘缓存.对DiskLruCache进行封装便于存取.

 在DiskLruCache中相对于LruCache是非常不方便利于存取的,它的API稍微有一些复杂.它需要一个Editor去Commit,类似于hibernate对象持久化一样,一般存储都是OutputStrem,所以我们必须要将要存储的数据转为OutputStream.所以为了开放方便便封装了一下存取.

    类有:DiskLruCache,DiskLruCacheHelper,Utils.其中DiskLruCache为磁盘缓存核心类,该类类似于LruCache算法,DiskLruCacheHepler是自己封装的存取类,Utils是工具类,封装了一些对文件名字进行MD5重命名,防止文件名字格式.

    存:

 

[java] view plain copy
 
  1. editor(String key).newOutputStream(0);//原有的方式  
  2.   
  3. put(String key, byte[] value)  
  4.   
  5. put(String key, String value)  
  6.   
  7. put(String key, Bitmap bitmap)  
  8.   
  9. put(String key, JSONArray jsonArray)  
  10.   
  11. put(String key, Serializable value)  
  12.   
  13. put(String key, Drawable value)  
  14.   
  15. put(String key, JSONObject jsonObject)  


    取:

 

 

[java] view plain copy
 
  1. InputStream get(String key);//原有的用法  
  2.   
  3. JSONObject getAsJson(String key)  
  4.   
  5. String getAsString(String key);  
  6.   
  7. <T> T getAsSerializable(String key)  
  8.   
  9. Bitmap getAsBitmap(String key)  
  10.   
  11. byte[] getAsBytes(String key)  
  12.   
  13. JSONArray getAsJSONArray(String key)  
  14.   
  15. Drawable getAsDrawable(String key)  



 

    DiskLruCacheHepler:

 

[cpp] view plain copy
 
  1. package com.softtanck.imageloader.imageloader.disklrucahe;  
  2.   
  3. import android.content.Context;  
  4. import android.graphics.Bitmap;  
  5. import android.graphics.drawable.Drawable;  
  6. import android.os.Environment;  
  7. import android.util.Log;  
  8.   
  9. import com.softtanck.imageloader.imageloader.utils.Utils;  
  10.   
  11. import org.json.JSONArray;  
  12. import org.json.JSONException;  
  13. import org.json.JSONObject;  
  14.   
  15. import java.io.BufferedWriter;  
  16. import java.io.ByteArrayOutputStream;  
  17. import java.io.File;  
  18. import java.io.IOException;  
  19. import java.io.InputStream;  
  20. import java.io.ObjectInputStream;  
  21. import java.io.ObjectOutputStream;  
  22. import java.io.OutputStream;  
  23. import java.io.OutputStreamWriter;  
  24. import java.io.Serializable;  
  25.   
  26. /** 
  27.  * 磁盘缓存帮助类 
  28.  */  
  29. public class DiskLruCacheHelper {  
  30.     private static final String DIR_NAME = "diskCache";  
  31.     private static final int MAX_COUNT = 5 * 1024 * 1024;  
  32.     private static final int DEFAULT_APP_VERSION = 1;  
  33.   
  34.     private static final String TAG = "DiskLruCacheHelper";  
  35.   
  36.     private DiskLruCache mDiskLruCache;  
  37.   
  38.     public DiskLruCacheHelper(Context context) throws IOException {  
  39.         mDiskLruCache = generateCache(context, DIR_NAME, MAX_COUNT);  
  40.     }  
  41.   
  42.     public DiskLruCacheHelper(Context context, String dirName) throws IOException {  
  43.         mDiskLruCache = generateCache(context, dirName, MAX_COUNT);  
  44.     }  
  45.   
  46.     public DiskLruCacheHelper(Context context, String dirName, int maxCount) throws IOException {  
  47.         mDiskLruCache = generateCache(context, dirName, maxCount);  
  48.     }  
  49.   
  50.     //custom cache dir  
  51.     public DiskLruCacheHelper(File dir) throws IOException {  
  52.         mDiskLruCache = generateCache(null, dir, MAX_COUNT);  
  53.     }  
  54.   
  55.     public DiskLruCacheHelper(Context context, File dir) throws IOException {  
  56.         mDiskLruCache = generateCache(context, dir, MAX_COUNT);  
  57.     }  
  58.   
  59.     public DiskLruCacheHelper(Context context, File dir, int maxCount) throws IOException {  
  60.         mDiskLruCache = generateCache(context, dir, maxCount);  
  61.     }  
  62.   
  63.     private DiskLruCache generateCache(Context context, File dir, int maxCount) throws IOException {  
  64.         if (!dir.exists() || !dir.isDirectory()) {  
  65.             throw new IllegalArgumentException(  
  66.                     dir + " is not a directory or does not exists. ");  
  67.         }  
  68.   
  69.         int appVersion = context == null ? DEFAULT_APP_VERSION : Utils.getAppVersion(context);  
  70.   
  71.         DiskLruCache diskLruCache = DiskLruCache.open(  
  72.                 dir,  
  73.                 appVersion,  
  74.                 DEFAULT_APP_VERSION,  
  75.                 maxCount);  
  76.   
  77.         return diskLruCache;  
  78.     }  
  79.   
  80.     private DiskLruCache generateCache(Context context, String dirName, int maxCount) throws IOException {  
  81.         DiskLruCache diskLruCache = DiskLruCache.open(  
  82.                 getDiskCacheDir(context, dirName),  
  83.                 Utils.getAppVersion(context),  
  84.                 DEFAULT_APP_VERSION,  
  85.                 maxCount);  
  86.         return diskLruCache;  
  87.     }  
  88.     // =======================================  
  89.     // ============== String 数据 读写 =============  
  90.     // =======================================  
  91.   
  92.     public void put(String key, String value) {  
  93.         DiskLruCache.Editor edit = null;  
  94.         BufferedWriter bw = null;  
  95.         try {  
  96.             edit = editor(key);  
  97.             if (edit == null) return;  
  98.             OutputStream os = edit.newOutputStream(0);  
  99.             bw = new BufferedWriter(new OutputStreamWriter(os));  
  100.             bw.write(value);  
  101.             edit.commit();//write CLEAN  
  102.         } catch (IOException e) {  
  103.             e.printStackTrace();  
  104.             try {  
  105.                 //s  
  106.                 edit.abort();//write REMOVE  
  107.             } catch (IOException e1) {  
  108.                 e1.printStackTrace();  
  109.             }  
  110.         } finally {  
  111.             try {  
  112.                 if (bw != null)  
  113.                     bw.close();  
  114.             } catch (IOException e) {  
  115.                 e.printStackTrace();  
  116.             }  
  117.         }  
  118.     }  
  119.   
  120.     public String getAsString(String key) {  
  121.         InputStream inputStream = null;  
  122.         try {  
  123.             //write READ  
  124.             inputStream = get(key);  
  125.             if (inputStream == null) return null;  
  126.             StringBuilder sb = new StringBuilder();  
  127.             int len = 0;  
  128.             byte[] buf = new byte[128];  
  129.             while ((len = inputStream.read(buf)) != -1) {  
  130.                 sb.append(new String(buf, 0, len));  
  131.             }  
  132.             return sb.toString();  
  133.   
  134.   
  135.         } catch (IOException e) {  
  136.             e.printStackTrace();  
  137.             if (inputStream != null)  
  138.                 try {  
  139.                     inputStream.close();  
  140.                 } catch (IOException e1) {  
  141.                     e1.printStackTrace();  
  142.                 }  
  143.         }  
  144.         return null;  
  145.     }  
  146.   
  147.   
  148.     public void put(String key, JSONObject jsonObject) {  
  149.         put(key, jsonObject.toString());  
  150.     }  
  151.   
  152.     public JSONObject getAsJson(String key) {  
  153.         String val = getAsString(key);  
  154.         try {  
  155.             if (val != null)  
  156.                 return new JSONObject(val);  
  157.         } catch (JSONException e) {  
  158.             e.printStackTrace();  
  159.         }  
  160.         return null;  
  161.     }  
  162.   
  163.     // =======================================  
  164.     // ============ JSONArray 数据 读写 =============  
  165.     // =======================================  
  166.   
  167.     public void put(String key, JSONArray jsonArray) {  
  168.         put(key, jsonArray.toString());  
  169.     }  
  170.   
  171.     public JSONArray getAsJSONArray(String key) {  
  172.         String JSONString = getAsString(key);  
  173.         try {  
  174.             JSONArray obj = new JSONArray(JSONString);  
  175.             return obj;  
  176.         } catch (Exception e) {  
  177.             e.printStackTrace();  
  178.             return null;  
  179.         }  
  180.     }  
  181.   
  182.     // =======================================  
  183.     // ============== byte 数据 读写 =============  
  184.     // =======================================  
  185.   
  186.     /** 
  187.      * 保存 byte数据 到 缓存中 
  188.      * 
  189.      * @param key   保存的key 
  190.      * @param value 保存的数据 
  191.      */  
  192.     public void put(String key, byte[] value) {  
  193.         OutputStream out = null;  
  194.         DiskLruCache.Editor editor = null;  
  195.         try {  
  196.             editor = editor(key);  
  197.             if (editor == null) {  
  198.                 return;  
  199.             }  
  200.             out = editor.newOutputStream(0);  
  201.             out.write(value);  
  202.             out.flush();  
  203.             editor.commit();//write CLEAN  
  204.         } catch (Exception e) {  
  205.             e.printStackTrace();  
  206.             try {  
  207.                 editor.abort();//write REMOVE  
  208.             } catch (IOException e1) {  
  209.                 e1.printStackTrace();  
  210.             }  
  211.   
  212.         } finally {  
  213.             if (out != null) {  
  214.                 try {  
  215.                     out.close();  
  216.                 } catch (IOException e) {  
  217.                     e.printStackTrace();  
  218.                 }  
  219.             }  
  220.         }  
  221.     }  
  222.   
  223.   
  224.     public byte[] getAsBytes(String key) {  
  225.         byte[] res = null;  
  226.         InputStream is = get(key);  
  227.         if (is == null) return null;  
  228.         ByteArrayOutputStream baos = new ByteArrayOutputStream();  
  229.         try {  
  230.             byte[] buf = new byte[256];  
  231.             int len = 0;  
  232.             while ((len = is.read(buf)) != -1) {  
  233.                 baos.write(buf, 0, len);  
  234.             }  
  235.             res = baos.toByteArray();  
  236.         } catch (IOException e) {  
  237.             e.printStackTrace();  
  238.         }  
  239.         return res;  
  240.     }  
  241.   
  242.   
  243.     // =======================================  
  244.     // ============== 序列化 数据 读写 =============  
  245.     // =======================================  
  246.     public void put(String key, Serializable value) {  
  247.         DiskLruCache.Editor editor = editor(key);  
  248.         ObjectOutputStream oos = null;  
  249.         if (editor == null) return;  
  250.         try {  
  251.             OutputStream os = editor.newOutputStream(0);  
  252.             oos = new ObjectOutputStream(os);  
  253.             oos.writeObject(value);  
  254.             oos.flush();  
  255.             editor.commit();  
  256.         } catch (IOException e) {  
  257.             e.printStackTrace();  
  258.             try {  
  259.                 editor.abort();  
  260.             } catch (IOException e1) {  
  261.                 e1.printStackTrace();  
  262.             }  
  263.         } finally {  
  264.             try {  
  265.                 if (oos != null)  
  266.                     oos.close();  
  267.             } catch (IOException e) {  
  268.                 e.printStackTrace();  
  269.             }  
  270.         }  
  271.     }  
  272.   
  273.     public <T> T getAsSerializable(String key) {  
  274.         T t = null;  
  275.         InputStream is = get(key);  
  276.         ObjectInputStream ois = null;  
  277.         if (is == null) return null;  
  278.         try {  
  279.             ois = new ObjectInputStream(is);  
  280.             t = (T) ois.readObject();  
  281.         } catch (ClassNotFoundException e) {  
  282.             e.printStackTrace();  
  283.         } catch (IOException e) {  
  284.             e.printStackTrace();  
  285.         } finally {  
  286.             try {  
  287.                 if (ois != null)  
  288.                     ois.close();  
  289.             } catch (IOException e) {  
  290.                 e.printStackTrace();  
  291.             }  
  292.         }  
  293.         return t;  
  294.     }  
  295.   
  296.     // =======================================  
  297.     // ============== bitmap 数据 读写 =============  
  298.     // =======================================  
  299.     public void put(String key, Bitmap bitmap) {  
  300.         put(key, Utils.bitmap2Bytes(bitmap));  
  301.     }  
  302.   
  303.     public Bitmap getAsBitmap(String key) {  
  304.         byte[] bytes = getAsBytes(key);  
  305.         if (bytes == null) return null;  
  306.         return Utils.bytes2Bitmap(bytes);  
  307.     }  
  308.   
  309.     // =======================================  
  310.     // ============= drawable 数据 读写 =============  
  311.     // =======================================  
  312.     public void put(String key, Drawable value) {  
  313.         put(key, Utils.drawable2Bitmap(value));  
  314.     }  
  315.   
  316.     public Drawable getAsDrawable(String key) {  
  317.         byte[] bytes = getAsBytes(key);  
  318.         if (bytes == null) {  
  319.             return null;  
  320.         }  
  321.         return Utils.bitmap2Drawable(Utils.bytes2Bitmap(bytes));  
  322.     }  
  323.   
  324.     // =======================================  
  325.     // ============= other methods =============  
  326.     // =======================================  
  327.     public boolean remove(String key) {  
  328.         try {  
  329.             key = Utils.hashKeyForDisk(key);  
  330.             return mDiskLruCache.remove(key);  
  331.         } catch (IOException e) {  
  332.             e.printStackTrace();  
  333.         }  
  334.         return false;  
  335.     }  
  336.   
  337.     public void close() throws IOException {  
  338.         mDiskLruCache.close();  
  339.     }  
  340.   
  341.     public void delete() throws IOException {  
  342.         mDiskLruCache.delete();  
  343.     }  
  344.   
  345.     public void flush() throws IOException {  
  346.         mDiskLruCache.flush();  
  347.     }  
  348.   
  349.     public boolean isClosed() {  
  350.         return mDiskLruCache.isClosed();  
  351.     }  
  352.   
  353.     public long size() {  
  354.         return mDiskLruCache.size();  
  355.     }  
  356.   
  357.     public void setMaxSize(long maxSize) {  
  358.         mDiskLruCache.setMaxSize(maxSize);  
  359.     }  
  360.   
  361.     public File getDirectory() {  
  362.         return mDiskLruCache.getDirectory();  
  363.     }  
  364.   
  365.     public long getMaxSize() {  
  366.         return mDiskLruCache.getMaxSize();  
  367.     }  
  368.   
  369.   
  370.     // =======================================  
  371.     // ===遇到文件比较大的,可以直接通过流读写 =====  
  372.     // =======================================  
  373.     //basic editor  
  374.     public DiskLruCache.Editor editor(String key) {  
  375.         try {  
  376.             key = Utils.hashKeyForDisk(key);  
  377.             //wirte DIRTY  
  378.             DiskLruCache.Editor edit = mDiskLruCache.edit(key);  
  379.             //edit maybe null :the entry is editing  
  380.             if (edit == null) {  
  381.                 Log.w(TAG, "the entry spcified key:" + key + " is editing by other . ");  
  382.             }  
  383.             return edit;  
  384.         } catch (IOException e) {  
  385.             e.printStackTrace();  
  386.         }  
  387.   
  388.         return null;  
  389.     }  
  390.   
  391.   
  392.     //basic get  
  393.     public InputStream get(String key) {  
  394.         try {  
  395.             DiskLruCache.Snapshot snapshot = mDiskLruCache.get(Utils.hashKeyForDisk(key));  
  396.             if (snapshot == null) //not find entry , or entry.readable = false  
  397.             {  
  398.                 Log.e(TAG, "not find entry , or entry.readable = false");  
  399.                 return null;  
  400.             }  
  401.             //write READ  
  402.             return snapshot.getInputStream(0);  
  403.   
  404.         } catch (IOException e) {  
  405.             e.printStackTrace();  
  406.             return null;  
  407.         }  
  408.   
  409.     }  
  410.   
  411.   
  412.     // =======================================  
  413.     // ============== 序列化 数据 读写 =============  
  414.     // =======================================  
  415.   
  416.     private File getDiskCacheDir(Context context, String uniqueName) {  
  417.         String cachePath;  
  418.         if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())  
  419.                 || !Environment.isExternalStorageRemovable()) {  
  420.             cachePath = context.getExternalCacheDir().getPath();  
  421.         } else {  
  422.             cachePath = context.getCacheDir().getPath();  
  423.         }  
  424.         return new File(cachePath + File.separator + uniqueName);  
  425.     }  
  426.   
  427. }  

完整代码:http://blog.csdn.net/u010316858/article/details/49300851

posted @ 2017-05-06 15:57  天涯海角路  阅读(735)  评论(0)    收藏  举报