如何读取和写入缓存文件?

时间:2015-10-30 08:09:38

标签: android caching

我想为我的appliaction保存一些缓存数据。我曾经通过在外部存储中保存数据来做到这一点,这很好。但我希望我的设备在应用程序设置中显示我的缓存大小但不是。我想这是因为我将数据保存在外部存储器中。我想要的是,关闭应用程序后,我的数据仍然存在,甚至关闭我的设备。现在我试图将我的文件保存在内部存储中,但是我在阅读文件时遇到了麻烦+设置中的缓存大小仍然是错误的。任何人都可以给我的方法是在应用程序缓存中写入和读取字符串吗?

1 个答案:

答案 0 :(得分:7)

我认为一切都清楚地解释了here ......:)

如果你有简单的数据,你可以像这样使用SharedPreferences:

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);
}

为了使用缓存,您必须使用方法

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

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

用这个写:

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

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

相关问题