我想为我的appliaction保存一些缓存数据.我曾经通过在外部存储中保存数据来做到这一点,这很好.但我希望我的设备在应用程序设置中显示我的缓存大小但不是.我想这是因为我将数据保存在外部存储器中.我想要的是,关闭应用程序后,我的数据仍然存在,甚至关闭我的设备.现在我试图将我的文件保存在内部存储器中但是我在阅读文件时遇到了麻烦+设置中的缓存大小仍然是错误的.任何人都可以给我的方法是在应用程序缓存中写入和读取字符串吗?
如果你有juste简单数据,你可以像这样使用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);
}
Run Code Online (Sandbox Code Playgroud)
为了使用缓存,您必须使用该方法
File file = new File(context.getCacheDir(), filename);
Run Code Online (Sandbox Code Playgroud)
返回一个可以编写和读取的File对象.
用这个写:
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(fcontent);
bw.close();
Run Code Online (Sandbox Code Playgroud)
请注意,如果系统缺少空间,Android可能会删除此文件,因此请勿使用此文件存储太多数据.(> 1MB)