Java tutorial
/** * Copyright (c) 2012-2013, Michael Yang ?? (www.yangfuhai.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.devilyang.musicstation.cache; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.RandomAccessFile; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import org.json.JSONArray; import org.json.JSONObject; import com.devilyang.musicstation.net.LogUtil; import android.content.Context; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.util.Log; /** * @author Michael Yangwww.yangfuhai.com update at 2013.08.07 */ public class ACache { public static final int TIME_HOUR = 60 * 60; public static final int TIME_DAY = TIME_HOUR * 24; private static final int MAX_SIZE = 1000 * 1000 * 50; // 50 mb private static final int MAX_COUNT = Integer.MAX_VALUE; // ???? private static Map<String, ACache> mInstanceMap = new HashMap<String, ACache>(); private ACacheManager mCacheManager; public static ACache get(Context ctx) { return get(ctx, "ACache"); } public static ACache get(Context ctx, String cacheName) { File f = new File(ctx.getCacheDir(), cacheName); return get(f, MAX_SIZE, MAX_COUNT); } public static ACache get(File cacheDir) { return get(cacheDir, MAX_SIZE, MAX_COUNT); } public static ACache get(Context ctx, long max_zise, int max_count) { File f = new File(ctx.getCacheDir(), "ACache"); return get(f, max_zise, max_count); } public static ACache get(File cacheDir, long max_zise, int max_count) { ACache aCache = mInstanceMap.get(cacheDir.getAbsoluteFile() + myPid()); if (aCache == null) { aCache = new ACache(cacheDir, max_zise, max_count); mInstanceMap.put(cacheDir.getAbsolutePath() + myPid(), aCache); } return aCache; } private static String myPid() { return "_" + android.os.Process.myPid(); } private ACache(File cacheDir, long max_size, int max_count) { if (!cacheDir.exists() && !cacheDir.mkdirs()) { throw new RuntimeException("can't make dirs in " + cacheDir.getAbsolutePath()); } mCacheManager = new ACacheManager(cacheDir, max_size, max_count); } // ======================================= // ============ String? ============== // ======================================= /** * ? String? * * @param key * ?key * @param value * ?String? */ public void put(String key, String value) { File file = mCacheManager.newFile(key); BufferedWriter out = null; try { out = new BufferedWriter(new FileWriter(file), 1024); out.write(value); } catch (IOException e) { e.printStackTrace(); } finally { if (out != null) { try { out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } } mCacheManager.put(file); } } /** * ? String? * * @param key * ?key * @param value * ?String? * @param saveTime * ??? */ public void put(String key, String value, int saveTime) { put(key, Utils.newStringWithDateInfo(saveTime, value)); } /** * ? String? * * @param key * @return String ? */ public String getAsString(String key) { File file = mCacheManager.get(key); if (!file.exists()) return null; boolean removeFile = false; BufferedReader in = null; try { in = new BufferedReader(new FileReader(file)); String readString = ""; String currentLine; while ((currentLine = in.readLine()) != null) { readString += currentLine; } Log.e("error", "readString = " + readString); if (!Utils.isDue(readString)) { LogUtil.i("error", "?"); return Utils.clearDateInfo(readString); } else { LogUtil.e("error", "?"); removeFile = true; return null; } } catch (IOException e) { Log.e("error", e.getLocalizedMessage()); e.printStackTrace(); return null; } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } if (removeFile) remove(key); } } // ======================================= // ============= JSONObject ? ============== // ======================================= /** * ? JSONObject? * * @param key * ?key * @param value * ?JSON? */ public void put(String key, JSONObject value) { put(key, value.toString()); } /** * ? JSONObject? * * @param key * ?key * @param value * ?JSONObject? * @param saveTime * ??? */ public void put(String key, JSONObject value, int saveTime) { put(key, value.toString(), saveTime); } /** * ?JSONObject? * * @param key * @return JSONObject? */ public JSONObject getAsJSONObject(String key) { String JSONString = getAsString(key); try { JSONObject obj = new JSONObject(JSONString); return obj; } catch (Exception e) { e.printStackTrace(); return null; } } // ======================================= // ============ JSONArray ? ============= // ======================================= /** * ? JSONArray? * * @param key * ?key * @param value * ?JSONArray? */ public void put(String key, JSONArray value) { put(key, value.toString()); } /** * ? JSONArray? * * @param key * ?key * @param value * ?JSONArray? * @param saveTime * ??? */ public void put(String key, JSONArray value, int saveTime) { put(key, value.toString(), saveTime); } /** * ?JSONArray? * * @param key * @return JSONArray? */ public JSONArray getAsJSONArray(String key) { String JSONString = getAsString(key); try { JSONArray obj = new JSONArray(JSONString); return obj; } catch (Exception e) { e.printStackTrace(); return null; } } // ======================================= // ============== byte ? ============= // ======================================= /** * ? byte? * * @param key * ?key * @param value * ?? */ public void put(String key, byte[] value) { File file = mCacheManager.newFile(key); FileOutputStream out = null; try { out = new FileOutputStream(file); out.write(value); } catch (Exception e) { e.printStackTrace(); } finally { if (out != null) { try { out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } } mCacheManager.put(file); } } /** * Cache for a stream * * @param key * the file name. * @return OutputStream stream for writing data. * @throws FileNotFoundException * if the file can not be created. */ public OutputStream put(String key) throws FileNotFoundException { return new xFileOutputStream(mCacheManager.newFile(key)); } /** * * @param key * the file name. * @return (InputStream or null) stream previously saved in cache. * @throws FileNotFoundException * if the file can not be opened */ public InputStream get(String key) throws FileNotFoundException { File file = mCacheManager.get(key); if (!file.exists()) return null; return new FileInputStream(file); } /** * ? byte? * * @param key * ?key * @param value * ?? * @param saveTime * ??? */ public void put(String key, byte[] value, int saveTime) { put(key, Utils.newByteArrayWithDateInfo(saveTime, value)); } /** * ? byte ? * * @param key * @return byte ? */ public byte[] getAsBinary(String key) { RandomAccessFile RAFile = null; boolean removeFile = false; try { File file = mCacheManager.get(key); if (!file.exists()) return null; RAFile = new RandomAccessFile(file, "r"); byte[] byteArray = new byte[(int) RAFile.length()]; RAFile.read(byteArray); if (!Utils.isDue(byteArray)) { return Utils.clearDateInfo(byteArray); } else { removeFile = true; return null; } } catch (Exception e) { e.printStackTrace(); return null; } finally { if (RAFile != null) { try { RAFile.close(); } catch (IOException e) { e.printStackTrace(); } } if (removeFile) remove(key); } } // ======================================= // ============= ? ? =============== // ======================================= /** * ? Serializable? * * @param key * ?key * @param value * ?value */ public void put(String key, Serializable value) { put(key, value, -1); } /** * ? Serializable? * * @param key * ?key * @param value * ?value * @param saveTime * ??? */ public void put(String key, Serializable value, long saveTime) { ByteArrayOutputStream baos = null; ObjectOutputStream oos = null; try { baos = new ByteArrayOutputStream(); oos = new ObjectOutputStream(baos); oos.writeObject(value); byte[] data = baos.toByteArray(); if (saveTime != -1) { put(key, data, saveTime); } else { put(key, data); } } catch (Exception e) { e.printStackTrace(); } finally { try { oos.close(); } catch (IOException e) { } } } /** * ? Serializable? * * @param key * @return Serializable ? */ public Object getAsObject(String key) { byte[] data = getAsBinary(key); if (data != null) { ByteArrayInputStream bais = null; ObjectInputStream ois = null; try { bais = new ByteArrayInputStream(data); ois = new ObjectInputStream(bais); Object reObject = ois.readObject(); return reObject; } catch (Exception e) { e.printStackTrace(); return null; } finally { try { if (bais != null) bais.close(); } catch (IOException e) { e.printStackTrace(); } try { if (ois != null) ois.close(); } catch (IOException e) { e.printStackTrace(); } } } return null; } // ======================================= // ============== bitmap ? ============= // ======================================= /** * ? bitmap * * @param key * ?key * @param value * ?bitmap? */ public void put(String key, Bitmap value) { put(key, Utils.Bitmap2Bytes(value)); } /** * ? bitmap * * @param key * ?key * @param value * ? bitmap ? * @param saveTime * ??? */ public void put(String key, Bitmap value, long saveTime) { put(key, Utils.Bitmap2Bytes(value), saveTime); } /** * ? bitmap ? * * @param key * @return bitmap ? */ public Bitmap getAsBitmap(String key) { if (getAsBinary(key) == null) { return null; } return Utils.Bytes2Bimap(getAsBinary(key)); } // ======================================= // ============= drawable ? ============= // ======================================= /** * ? drawable * * @param key * ?key * @param value * ?drawable? */ public void put(String key, Drawable value) { put(key, Utils.drawable2Bitmap(value)); } /** * ? drawable * * @param key * ?key * @param value * ? drawable ? * @param saveTime * ??? */ public void put(String key, Drawable value, int saveTime) { put(key, Utils.drawable2Bitmap(value), saveTime); } /** * ? Drawable ? * * @param key * @return Drawable ? */ public Drawable getAsDrawable(String key) { if (getAsBinary(key) == null) { return null; } return Utils.bitmap2Drawable(Utils.Bytes2Bimap(getAsBinary(key))); } /** * ? * * @param key * @return value */ public File file(String key) { File f = mCacheManager.newFile(key); if (f.exists()) return f; return null; } /** * ?key * * @param key * @return ?? */ public boolean remove(String key) { return mCacheManager.remove(key); } /** * ? */ public void clear() { mCacheManager.clear(); } /** * Provides a means to save a cached file before the data are available. * Since writing about the file is complete, and its close method is called, * its contents will be registered in the cache. Example of use: * * ACache cache = new ACache(this) try { OutputStream stream = * cache.put("myFileName") stream.write("some bytes".getBytes()); // now * update cache! stream.close(); } catch(FileNotFoundException e){ * e.printStackTrace() } */ class xFileOutputStream extends FileOutputStream { File file; public xFileOutputStream(File file) throws FileNotFoundException { super(file); this.file = file; } public void close() throws IOException { super.close(); mCacheManager.put(file); } } }