cache和files目录的区别

本文通过实践演示了Android中cache与files目录的区别。通过创建简单的应用,对比了两者在文件存储上的不同行为,指出cache适合存放不重要的大文件如图片,而files更适合存储重要数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值