如何读写文件到我的缓存

如何读写文件到我的缓存

本文介绍了如何读写文件到我的缓存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想保存一些缓存数据供我使用。我曾经通过将数据保存在外部存储中来做到这一点,并且效果很好。但是我希望我的设备在应用程序设置中显示我的缓存大小,但事实并非如此。我猜这是因为我将数据保存在外部存储中。我想要的是关闭程序后甚至关闭设备后,我的数据仍然存在。现在,我尝试将文件保存在内部存储器中,但是在读取文件时遇到了麻烦,而且设置中的缓存大小仍然不正确。谁能给我方法在应用程序缓存中的文件中写入和读取字符串的方法吗? ...:)



如果您只拥有简单数据,则可以使用SharedPreferences例如:

  public static void writeString(Context context,final String KEY,String property){
SharedPreferences.Editor编辑器= context.getSharedPreferences(Constants.SHARED_PREFERENCES_KEY,context.MODE_PRIVATE).edit();
editor.putString(KEY,property);
editor.commit();
}

public static String readString(Context context,final String KEY){
返回context.getSharedPreferences(Constants.SHARED_PREFERENCES_KEY,context.MODE_PRIVATE).getString(KEY,null) ;
}

要使用缓存,必须使用方法

 文件=新文件(context.getCacheDir(),filename); 

返回一个可以读写的File对象。



使用它来编写:

  FileWriter fw = new FileWriter(file.getAbsoluteFile()); 
BufferedWriter bw =新的BufferedWriter(fw);
bw.write(fcontent);
bw.close();

请注意,如果系统空间不足,Android可能会删除此文件,因此请不要使用它来存储太多数据。 (> 1MB)


I want to save some cache data for my appliaction. I used to do this by saving the data in the external storage and this worked fine. But I want my device to show my cache size in the app settings but It doesn´t. I guess this is because I save the data in external storage. What I want is that my data still exists aufter closing the app or even swichen off my device. Now I tried to save my files in the internal storage but I have troubles reading the files + the cache size is still wrong in settings. Can anyone give me the methodes do write and read strings into files in the applications cache please?

解决方案

I think everything is clearly explained here... :)

if you have juste simple data, you can use SharedPreferences like this for example :

public static void writeString(Context context, final String KEY, String property) {
    SharedPreferences.Editor editor = context.getSharedPreferences(Constants.SHARED_PREFERENCES_KEY, context.MODE_PRIVATE).edit();
    editor.putString(KEY, property);
    editor.commit();
}

public static String readString(Context context, final String KEY) {
    return context.getSharedPreferences(Constants.SHARED_PREFERENCES_KEY, context.MODE_PRIVATE).getString(KEY, null);
}

in order to use the cache, you have to use the method

File file = new File(context.getCacheDir(), filename);

which return a File object you can write and read on.

Use this to write :

FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(fcontent);
bw.close();

Be aware that Android may delete this file if the system lack space, so don't use this to store too much data. ( > 1MB)

这篇关于如何读写文件到我的缓存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 22:54