How to read and write files to my cache?

2019-05-13 05:02发布

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?

1条回答
老娘就宠你
2楼-- · 2019-05-13 05:41

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)

查看更多
登录 后发表回答