How to read and write files to my cache?

两盒软妹~` 提交于 2020-01-13 03:36:07

问题


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:


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)



来源:https://stackoverflow.com/questions/33431314/how-to-read-and-write-files-to-my-cache

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!