Android数据存储——Cache存储

本文介绍了Android中Cache存储的使用,数据存放在/data/data/<packagename>/cache/目录下,并设置时间限制自动回收。通过点击事件实现数据写入缓存,通过输入框获取数据并利用输出流写入文件。

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

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的初始化中添加两个参数,然后利用输出流将得到的数据写入缓存中
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值