DiskLruCache属于目前最好的Disk Cache库了,但是由于其的存取API,并不是特别好用。
ASimpleCache 提供的API属于比较好用的了。
于是萌生想法,对于其公开的API进行扩展,对外除了原有的存取方式以外,提供类似ASimpleCache那样比较简单的API用于存储,而内部的核心实现,依然是DiskLruCache原本的。
put(Stringkey, Bitmapbitmap)
put(Stringkey, byte[] value)
put(Stringkey, Stringvalue)
put(Stringkey, JSONObjectjsonObject)
put(Stringkey, JSONArrayjsonArray)
put(Stringkey, Serializablevalue)
put(Stringkey, Drawablevalue)
editor(Stringkey).newOutputStream(0);//原有的方式StringgetAsString(Stringkey);
JSONObjectgetAsJson(Stringkey)
JSONArraygetAsJSONArray(Stringkey)
<T> TgetAsSerializable(Stringkey)
BitmapgetAsBitmap(Stringkey)
byte[] getAsBytes(Stringkey)
DrawablegetAsDrawable(Stringkey)
InputStreamget(Stringkey);//原有的用法publicclassCacheTestextendsAndroidTestCase
{
DiskLruCacheHelperhelper;
privatestaticfinalStringTAG = "CacheTest";
@OverrideprotectedvoidsetUp() throwsException
{
super.setUp();
Log.e(TAG, "setUp");
helper = newDiskLruCacheHelper(getContext());
}
publicvoidtestString() throwsIOException
{
helper.put("testString", "张鸿洋");
assertEquals("张鸿洋", helper.getAsString("testString"));
}
publicvoidtestGetStringWithoutVal() throwsIOException
{
assertEquals(null, helper.getAsString("zhy------zzzzz"));
}
publicvoidtestJson()
{
try
{
JSONObjectjsonObject = newJSONObject("{\"name\":\"zhy\"}");
helper.put("testJson", jsonObject);
assertEquals(jsonObject.toString(), helper.getAsJson("testJson").toString());
} catch (JSONExceptione)
{
e.printStackTrace();
}
}
publicvoidtestSerializable()
{
Useru = newUser();
u.name = "张鸿洋";
helper.put("testSerializable", u);
Useru2 = helper.getAsSerializable("testSerializable");
assertEquals(u.name, u2.name);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
publicvoidtestBitmap()
{
Bitmapbm = BitmapFactory.decodeResource(getContext().getResources(), R.mipmap.ic_launcher);
helper.put("testBitmap", bm);
Bitmapbm2 = helper.getAsBitmap("testBitmap");
assertEquals(bm.getByteCount(), bm2.getByteCount());
}
publicvoidtestDrawable()
{
Drawabled = getContext().getResources().getDrawable(R.mipmap.ic_launcher);
helper.put("testDrawable", d);
Drawabled2 = helper.getAsDrawable("testDrawable");
assertNotNull(d2);
}
privatestaticclassUserimplementsSerializable
{
Stringname;
}
@OverrideprotectedvoidtearDown() throwsException
{
super.tearDown();
Log.e(TAG, "tearDown");
helper.close();
}
}