android 文件缓存工具类

/**
* Json数据缓存的工具类
*
*/
public class CacheDataSd {


/**
*
* @param context 当前对象
* @param dir 创建的文件
* @param requesturl 标志字段
* @param jsondata json数据
*/
public static void SaveSDByteArray(Context context, String dir,
String requesturl, String jsondata) {
String Directory=context.getExternalCacheDir()+File.separator +dir+File.separator;
//首先判断目录是否存在,再具体判断文件是否存在
//加载完成进行存储
File dirs=new File(Directory);
File cac=new File(dirs,requesturl);
if(dirs.exists() && dirs.length()>0){
if(cac.exists() && cac.length()>0){
//不做任何操作
}else{
try {
byte[] data = jsondata.getBytes("utf-8");
FileOutputStream outf;
outf=new FileOutputStream(Directory+requesturl);
BufferedOutputStream bufferout = new BufferedOutputStream(outf);
bufferout.write(data);
bufferout.flush();
bufferout.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}else{
dirs.mkdirs();
try {
byte[] data = jsondata.getBytes("utf-8");
FileOutputStream outf;
outf=new FileOutputStream(Directory+requesturl);
BufferedOutputStream bufferout = new BufferedOutputStream(outf);
bufferout.write(data);
bufferout.flush();
bufferout.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

/**
*
* @param context 当前对象
* @param dir 创建的文件
* @param requesturl 标志字段
* @param jsondata json数据
*/
public static byte[] ReadSDByteArray(Context context, String dir,
String requesturl) {
ByteArrayOutputStream out;
try {
BufferedInputStream in = new BufferedInputStream(
new FileInputStream(context.getExternalCacheDir()+File.separator + dir + File.separator +requesturl));
out = new ByteArrayOutputStream(1024);
byte[] temp = new byte[1024];
int size = 0;
while ((size = in.read(temp)) != -1) {
out.write(temp, 0, size);
}
in.close();
byte[] content = out.toByteArray();
return content;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}

posted @ 2014-11-14 16:31  Target100  阅读(1129)  评论(0编辑  收藏  举报