Writing of the "Android Note" HDD Cache tool Class

Source: Internet
Author: User

Disklrucache (Https://github.com/JakeWharton/DiskLruCache) must be familiar to everyone. (see here for unfamiliar), it is an open source library written by Jakewharton, which provides a solution for hard disk caching.

But the API of the library is relatively simple, and sometimes it is not enough for us to use. For example, if you want to return the data in the cache as bitmap, the API does not provide such a method, we must obtain the input stream through the snapshot returned by the Disklrucache#get method, and then turn the flow into bitmap. In addition, Disklrucache must be built to pass variables such as Versioncode,cachepath, and in real development, Versioncode is usually the application version number, CachePath is also relatively fixed (either the SD cache directory or the local cache directory , it's too boring to write code to get the version number, and so on, every time you build Disklrucache. For example, the write cache needs to specify key, and this key in the project is usually a URL, and the URL may have special characters, which will cause the write cache failure, we'd better encode the URL, and then use the encoded key, and in the API does not provide a similar method.    In view of this, I have written a Disklrucache-based tool class that further simplifies caching operations. The methods in the master of this tool class are all static and can be called directly. Its functions are: 1. Build the Cache object; 2. Read the cache. Read the cache as string/stream/bitmap;3. Write Cache. You can write the string/file/stream/bitmap to the cache and support asynchronous writes.
Having said so much, let's see how this tool class is written.
Package Com.jakewharton.disklrucache;import Java.io.bufferedinputstream;import Java.io.file;import Java.io.fileinputstream;import Java.io.filenotfoundexception;import Java.io.ioexception;import Java.io.inputstream;import Java.io.outputstream;import Java.security.messagedigest;import Java.security.nosuchalgorithmexception;import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;import Android.content.context;import Android.content.pm.packagemanager;import Android.content.pm.packagemanager.namenotfoundexception;import Android.graphics.bitmap;import Android.graphics.bitmap.compressformat;import Android.graphics.bitmapfactory;import android.os.Environment; Import android.text.textutils;/** * @author ROWANDJJ * *disklrucache Auxiliary tool class (Disklrucache:http://jakewharton.github.io /disklrucache) * Provides methods for creating/reading/writing caches, and supports asynchronous cache writes. */public class Disklrucachehelper{private static final long default_max_size = 10*1024*1024;private static Executorservice Service = null;/** * * Create DISKLRUcache instance, the default version number is the current app version number, the cache location is specified by Getdiskcachedir * @param context Context * @param cachedirname Cache folder name * @param maxSize cache maximum, units is a byte * @return the creation of a successful return Disklrucache instance otherwise returns null */public static Disklrucache Createcache (Context context,string Cachedirname,long maxSize) {Disklrucache cache = null;try{cache = Disklrucache.open (Getdiskcachedir (Cachedirname, context), getappversion (context), 1, maxSize);} catch (IOException e) {e.printstacktrace ();} return cache;} /** * Returns a Disklrucache instance with a default size of 10Mb * @param context * @param cachedirname * @return Create a successful return Disklrucache instance or return NULL */ public static Disklrucache Createcache (context context,string cachedirname) {return Createcache (context, Cachedirname, default_max_size);} /** * Write picture to cache */public static Boolean writebitmaptocache (Disklrucache cache,bitmap bitmap,string URL) {return Writebitmaptocache (cache, bitmap, URL, compressformat.jpeg,100);} /** * Asynchronously writes a picture to the cache. No results will be written. * @param cache * @param bitmap * @param url */public static void Asyncwritebitmaptocache (fInal disklrucache cache,final Bitmap bitmap,final String URL) {if (service = = null) Service = Executors.newsinglethreadexecutor (); Service.execute (new Runnable () {@Overridepublic void run () {Writebitmaptocache ( Cache, bitmap, URL);});} /** * Write picture to cache * @param Cache Cache Object * @param bitmap Picture object * @param URL is used to identify the unique name of the bitmap, usually the picture URL * @return True indicates that the write cache was successful otherwise fals E */public Static Boolean Writebitmaptocache (Disklrucache cache,bitmap bitmap,string url,compressformat format, int Quality) {if (cache = = NULL | | bitmap = = NULL | | url = = NULL | | Textutils.isempty (URL)) return false;try{disklrucache.editor Editor = Cache.edit (GenerateKey (URL)); if (Editor! = null) {OutputStream out = Editor.newoutputstream (0); if (Bitmap.compress (format,quality, out)) {editor.commit (); return true;} Else{editor.abort ();}}} catch (IOException e) {e.printstacktrace ();} return false;} /** * Asynchronously writes a picture to the cache. No results will be written. */public static void Asyncwritebitmaptocache (final disklrucache cache,final Bitmap bitmap,final String url,final Compressformat foRmat, final int quality) {if (service = = null) service = Executors.newsinglethreadexecutor (); Service.execute (New Runnable () {@Overridepublic void run () {Writebitmaptocache (cache, Bitmap, url,format,quality);});} /** * Asynchronously writes the Inputstram stream to the cache, and no write results are returned. */public static void Asyncwritestreamtocache (final disklrucache cache,final inputstream in,final String URL) {if (service = = null) service = Executors.newsinglethreadexecutor (); Service.execute (new Runnable () {@Overridepublic void run () { Asyncwritestreamtocache (cache, in, URL);});} /** * writes Inputstram stream to cache * @param cache * @param in * @param URL * @return */public static Boolean Writestreamtocache (DISKLR Ucache cache,inputstream in,string URL) {if (cache = = NULL | | in = NULL | | url = = null| | Textutils.isempty (URL)) return false;disklrucache.editor Editor = Null;try{editor = Cache.edit (GenerateKey (URL)); Editor! = null) {OutputStream out = Editor.newoutputstream (0); Bufferedinputstream bin = new Bufferedinputstream (in); byte[] buffer = new Byte[1024];int len= 0;while (len = bin.read (buffer))! =-1) {out.write (buffer, 0, Len); Out.flush ();} Editor.commit (); return true;}} catch (IOException e) {e.printstacktrace ();} return false;} /** * Asynchronously writes a file to the cache, and no write results are returned. */public static void Asyncwritefiletocache (final disklrucache cache,final File file,final String URL) {if (service = = null) Service = Executors.newsinglethreadexecutor (); Service.execute (new Runnable () {@Overridepublic void run () { Writefiletocache (cache, file, URL);});} /** * Write file to cache * @return True indicates successful write or write failed */public static Boolean Writefiletocache (Disklrucache cache,file file,string URL) {if (cache = = NULL | | file = NULL | | url = = NULL | |!file.exists () | | Textutils.isempty (URL)) {return false;} FileInputStream fin = Null;try{fin = new FileInputStream (file),} catch (FileNotFoundException e) {e.printstacktrace ();} Return Writestreamtocache (cache, fin, url);} /** * Asynchronously writes a string to the cache and will not return write results */public static void Asyncwritestringtocache (final disklrucache cache,final string str,final String URL) {if (Service = = NULL) service = Executors.newsinglethreadexecutor (); Service.execute (new Runnable () {@Overridepublic void run () { Writestringtocache (cache, str, URL);});} /** * Write String to cache * @param cache * @param str * @param URL * @return */public static Boolean Writestringtocache (Disklrucache cache,string str,string URL) {if (cache = = NULL | | str = = NULL | | url = = NULL | | Textutils.isempty (URL) | | Textutils.isempty (str)) {return false;} Disklrucache.editor editor = Null;try{editor = Cache.edit (GenerateKey (URL)); if (editor! = null) {OutputStream out = Editor . Newoutputstream (0); Out.write (Str.getbytes ()); Out.flush (); Editor.commit (); return true;} catch (IOException e) {e.printstacktrace ();} return false;} /** * Stop the thread that is writing the cache internally, * This will cause the partial write cache task to fail. */public static void Stop () {if (service! = null) Service.shutdownnow ();} /** * * Gets the cache based on the URL and returns the result as a string * @param cache * @param URL * @return Success returns a string otherwise null */public static string READCA chetostring (disklrucache cache,string URL) {if (cache = = NULL | | url = = NULL | | Textutils. IsEmpty (URL)) return null; String key = GenerateKey (URL);D isklrucache.snapshot Snapshot = Null;try{snapshot = Cache.get (key); if (Snapshot! = null) { InputStream in = Snapshot.getinputstream (0);  StringBuilder builder = new StringBuilder (1024*2); int len = 0;byte[] buffer = new Byte[1024];while (len = in.read (buffer)) ! =-1) {Builder.append (new String (Buffer,0,len));} return builder.tostring ();}} catch (Exception e) {e.printstacktrace ();} return null;}  /** * Gets the cache based on the URL and returns the cache in inputstream form * * @param cache disklrucache instance * @param URL Cache name * @return hit returns InputStream stream otherwise null is returned */public static InputStream readcachetoinputstream (Disklrucache cache,string URL) {if (cache = = NULL | | url = = NULL | | Textutils.isempty (URL)) return null; String key = GenerateKey (URL);D isklrucache.snapshot Snapshot = Null;try{snapshot = Cache.get (key);} catch (IOException e) {E.printstacktrace ();} if (snapshot! = null) return Snapshot.getinputstream (0); return null;} /** * Gets the cache based on the URL and returns the cache in bitmap form * @param cache * @param URL * @returnreturn BITMAP, otherwise null */public static Bitmap readcachetobitmap (Disklrucache cache,string URL) {InputStream in = Readcachetoinputstream (cache, URL); if (in = null) return Bitmapfactory.decodestream (in); return null;} /** * Get cache file path (prefer SD card) * @param cachedirname Cache folder name * @param context context * @return */public static file Getdiskcachedir ( String Cachedirname,context Context) {string cachedir;if (Environment.getexternalstoragestate (). Equals ( environment.media_mounted) &&! Environment.isexternalstorageremovable ()) {Cachedir = Getexternalcachedir (context); if (Cachedir = = null)// Some models returned Nullcachedir = Getinternalcachedir (context);} Else{cachedir = Getinternalcachedir (context);} File dir = new file (cachedir,cachedirname), if (!dir.exists ()) dir.mkdirs (); return dir;}  /** * Gets the current app version number * @param context context * @return Current app version number */public static int getappversion (context context) {Packagemanager Manager = Context.getpackagemanager (); int code = 1;try{code = Manager.getpackageinfo (Context.getpackagename (), 0). VersioncOde;} catch (Namenotfoundexception e) {e.printstacktrace ();} return code;} /** * Removes the specified cache according to the specified URL * Note: Please do not use Disklrucache.remove () * * @param cache * @param URL * @return */public static Boolean R emove (disklrucache cache,string URL) {if (cache = = NULL | | url = = NULL | | Textutils.isempty (URL)) {return false;} Try{return cache.remove (GenerateKey (URL)),} catch (IOException e) {e.printstacktrace ();} return false;} /** * Generates a new key based on the original key to guarantee the legitimacy of the name of the key * @param key primitive key, usually URL * @return */public static string GenerateKey (String key) {string Cachek Ey;try{messagedigest Digest = messagedigest.getinstance ("MD5");d Igest.update (Key.getbytes ()); CacheKey = Bytestohexstring (Digest.digest ());}  catch (NoSuchAlgorithmException e) {e.printstacktrace (); CacheKey = String.valueof (Key.hashcode ()); }return CacheKey;} private static String bytestohexstring (byte[] bytes) {StringBuilder builder = new StringBuilder (); for (int i = 0; i < byt Es.length; i++) {String hex = integer.tohexstring (0xff&bytes[i]); if (hex.length () = = 1) BuildEr.append (' 0 '); builder.append (hex);} return builder.tostring ();} private static String Getexternalcachedir (context context) {File dir = Context.getexternalcachedir (); if (dir = = null) Return Null;if (!dir.exists ()) dir.mkdirs (); return Dir.getpath ();} private static String Getinternalcachedir (context context) {File dir = Context.getcachedir (); if (!dir.exists ()) Dir.mkdirs (); return Dir.getpath ();}}
The code is simple, and there are comments, I will not explain too much. Later in development, if you need to build Disklrucache, call Disklrucachehelper.createcache, fetch the cache callDisklrucachehelper.Readcachetoxx, write cache callDisklrucachehelper.writexxtocache, asynchronous write callDisklrucachehelper.asyncwritexxtocache, removing the specified cache callDisklrucachehelper.remove. Isn't it convenient?
GitHub Address: Https://github.com/Rowandjj/DiskLruCacheHelper

Writing of the "Android Note" HDD Cache tool Class

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.