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

Android数据存储——Cache存储

2015-09-07 21:19 357 查看
Cache存储表示存储的位置在缓存中,缓存中的数据会有一个最后生成时间,可以设置一个时间长度让数据自动被回收销毁。

存储位置依然为/data/data/<packagename>/cache/目录下,创建一个文件,然后就跟文件存储一样,向文件中写入数据即可。

同样首先定义一个输入框来获取要写入缓存的数据,然后定义一个按钮通过点击事件来完成数据的写入

<EditText
android:id="@+id/edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="写入数据"/>
<Button
android:id="@+id/button_write_cache"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="将数据写入缓存"/>


在MainActivity添加按钮的点击事件

private void writeCache() {
File file=new File(getCacheDir(),"Cachedata");
//两个参数,第一个得到cache的绝对路径,第二个参数是文件名
if (!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
FileOutputStream outputStream= null;
try {
outputStream =new FileOutputStream(file);
BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(outputStream));
bw.write(mEditText.getText().toString());
bw.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}


可以看到在file的初始化中添加两个参数,然后利用输出流将得到的数据写入缓存中

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