以下是我的使用DiskLruCache的部分代码
String str = Environment.getExternalStorageDirectory().getCanonicalPath() + "/2indextest";
File cachePath=new File(str);
if(!cachePath.exists()) cachePath.mkdirs();
myDiskLrucache=DiskLruCache.open(cachePath, 1, 2, 50 * 1024 * 1024); //note that the 3rd param is 2 here
//get the data from internet,and write into the cache
public void writeToCache(final String uri,final String text)
{
new Thread()
{
public void run()
{
try {
String key = "test";
editor = myDiskLrucache.edit(key);
outputStream=editor.newOutputStream(0);
if(download(uri, outputStream)) //the function download(...) is defined by myself,I will show it under this function
editor.commit();
else editor.abort();
index2=editor.newOutputStream(1);
if(writeTextToStream(text,index2)) //这个writeTextToStream函数也是我自定义的,下面会贴出函数定义代码
editor.commit(); //I think the error happens here,when writing the data with the index of 1 into the cache
else editor.abort();
myDiskLrucache.flush();
Message msg=myHandler.obtainMessage();
msg.what=1;
myHandler.sendMessage(msg);
}
catch(Exception e)
{
Log.e("this","some error happen when writing into the cache"+e);
}
}
}.start();
}
private boolean download(String uri,OutputStream output)
{
try {
URL url = new URL(uri);
HttpURLConnection con=(HttpURLConnection)url.openConnection();
BufferedInputStream in=new BufferedInputStream(con.getInputStream());
BufferedOutputStream out=new BufferedOutputStream(output);
int b;
while((b=in.read())!=-1)
out.write(b);
in.close();
out.close();
}
catch(Exception e)
{
Log.e("this",e.toString());
}
return true;
}
private boolean writeTextToStream(String text,OutputStream out) throws Exception
{
ByteArrayInputStream inputStream=new ByteArrayInputStream(text.getBytes());
int b;
while((b=inputStream.read())!=-1)
out.write(b);
inputStream.close();
out.close();
return true;
}
以上是部分代码,以下是logcat