在10min实现一个简易图片查看器(图片缓存)中我们使用到了Cache缓存。那么cache和files目录究竟有什么区别呢?今天我们一起来探索一下。
1.写好布局文件,2个Button分别绑定2个click事件,实现cache和files:
<Button
android:onClick="clickCache"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="click_cache"
/>
<Button
android:onClick="clickFiledir"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="click_filedir"
/>
2.写好Java核心代码,完成2个点击事件:
public void clickCache(View v){
File file = new File(getCacheDir(),"info.txt");
try {
FileOutputStream fileOutputStream = new FileOutputStream(file);
fileOutputStream.write("Hello World.".getBytes());
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void clickFiledir(View v){
try {
FileOutputStream fileOutputStream = openFileOutput("info.txt",0);
fileOutputStream.write("Hello World.".getBytes());
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
3.运行APP,探索结果:
分别点击两个Button,看一下文件目录:
相应生成cache和files目录。
然后我们进入模拟器的设置界面:
点击Clear cache。清除cache目录。
点击Clear data。清除cache和files目录。
因此,一般的不重要且频繁使用的大文件如图片可以使用cache,重要的文件可以使用files。