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

来源:互联网 发布:反电信网络诈骗 编辑:程序博客网 时间:2024/06/11 18:34
  • 数据存储到缓存中: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 "读取缓存失败";        }    }
0 0
原创粉丝点击