您的位置:首页 > 移动开发 > Android开发

Android存储(读取)之缓存CachesDir存储

2016-05-15 11:31 537 查看
数据存储到缓存中:data/data/包名/caches/,储存在缓存里的文件,当内存不足时,会自动释放掉



也可以点击清除缓存来清除数据



// 把String保存到私有文件夹中:data/data/包名/files/
StoreUtils.storeStringToCachesDir(this, "cachesDir", "ha.txt");
//读取data/data/包名/files/中的文件
String data = StoreUtils.readStringFromCachesDir(new File(getCacheDir(), "ha.txt"));


/**
* 数据存储到缓存中:data/data/包名/caches/
* @param context 上下文
* @param content 要保存的内容Sting
* @param fileName 保存内容的文件名称
* 具体代码与storeStringToFilesDir是一摸一样的,仅仅是改了个目录context.getCacheDir()
*                 除了目录不同就是,储存在缓存里的文件,当内存不足时,会自动释放掉,
*                 也可以点击清除缓存,来释放
*/
public static void storeStringToCachesDir(Context context, String content, String fileName) {
try {
File file = new File(context.getCacheDir(), fileName);
FileOutputStream fos = new FileOutputStream(file);
fos.write(content.getBytes());
fos.close();
Toast.makeText(context, "存储数据到CachesDir成功", Toast.LENGTH_SHORT).show();
}  catch (IOException e) {
e.printStackTrace();
Toast.makeText(context, "存储数据到CachesDir失败", Toast.LENGTH_SHORT).show();
}
}

/**
* 从私有文件夹中数读取据:data/data/包名/caches/
* @param file  data/data/包名/caches/下的文件
* @return String内容
* 代码与readStringFromFilesDir完全一样
*/
public static String readStringFromCachesDir(File file) {

try {
FileInputStream fis = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String content = "";
String tmp;
while ((tmp = br.readLine()) != null) {
content += tmp;
}
br.close();
fis.close();
return content;
} catch (FileNotFoundException e) {
e.printStackTrace();
return "读取缓存失败,不存在此文件,请核对文件路径、文件名";
} catch (Exception e) {
e.printStackTrace();
return "读取缓存失败";
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: