Silicon Valley News 10-data cache, Silicon Valley 10-Cache
1. Store strings in SharedPreferences
/*** Cache text data ** @ param context * @ param key * @ param value */public static void putString (Context context, String key, String value) {if (Environment. getExternalStorageState (). equals (Environment. MEDIA_MOUNTED) {// mnt/sdcard/beijingnews/files/llkskljskljklsjklsllsltry {String fileName = MD5Encoder. encode (key); // llkskljskljklsjklsllsl // mnt/sdcard/beijingnews/files/llkskljskljklsjklsllslslfile file = New File (Environment. getExternalStorageDirectory () + "/beijingnews/files", fileName); File parentFile = file. getParentFile (); // mnt/sdcard/beijingnews/filesif (! ParentFile. exists () {// create the directory parentFile. mkdirs ();} if (! File. exists () {file. createNewFile ();} // Save the text data FileOutputStream fileOutputStream = new FileOutputStream (file); fileOutputStream. write (value. getBytes (); fileOutputStream. close ();} catch (Exception e) {e. printStackTrace (); LogUtil. e ("text data cache failed") ;}} else {SharedPreferences sp = context. getSharedPreferences ("atguigu", Context. MODE_PRIVATE); sp. edit (). putString (key, value ). commit ();}}
2. Get the stored string from SharedPreferences
/*** Get the cached text information ** @ param context * @ param key * @ return */public static String getString (Context context, String key) {String result = ""; if (Environment. getExternalStorageState (). equals (Environment. MEDIA_MOUNTED) {try {String fileName = MD5Encoder. encode (key); // llkskljskljklsjklsllsl // mnt/sdcard/beijingnews/files/llkskljskljklsjklsllslFile file = new File (Environment. getExternalStorageDirector Y () + "/beijingnews/files", fileName); if (file. exists () {FileInputStream is = new FileInputStream (file); ByteArrayOutputStream stream = new ByteArrayOutputStream (); byte [] buffer = new byte [1024]; int length; while (length = is. read (buffer ))! =-1) {stream. write (buffer, 0, length);} is. close (); stream. close (); result = stream. toString () ;}} catch (Exception e) {e. printStackTrace (); LogUtil. e ("Image Retrieval failed") ;}} else {SharedPreferences sp = context. getSharedPreferences ("atguigu", Context. MODE_PRIVATE); result = sp. getString (key, "");} return result ;}