如何备份共享preferences到SD卡? [英] How can I backup SharedPreferences to SD card?
问题描述
我在很多地方看到,这是一个问题要复制的共享preferences文件到SD卡上,因为各厂商的地方。它在其他地方。我想备份在SD卡上没有马瑟哪里是文件的位置。
I saw in a lot of places that it's a problem to copy the SharedPreferences file to the sd card because every manufacturer place it somewhere else. I want to backup on the sd card no mather where is the file located.
推荐答案
在共享preferences
接口包含一个名为方法 GETALL()
返回的键值对的映射。因此,而不是复制文件本身,我只是序列化地图上,从这个方法返回,然后检索回来之后。
The SharedPreferences
interface contains a method called getAll()
which returns a map with the key-value pairs. So instead of copying the file itself, I just serialize the map that being returned from this method and then retrieve it back afterwards.
有些code:
private boolean saveSharedPreferencesToFile(File dst) {
boolean res = false;
ObjectOutputStream output = null;
try {
output = new ObjectOutputStream(new FileOutputStream(dst));
SharedPreferences pref =
getSharedPreferences(prefName, MODE_PRIVATE);
output.writeObject(pref.getAll());
res = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (output != null) {
output.flush();
output.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return res;
}
@SuppressWarnings({ "unchecked" })
private boolean loadSharedPreferencesFromFile(File src) {
boolean res = false;
ObjectInputStream input = null;
try {
input = new ObjectInputStream(new FileInputStream(src));
Editor prefEdit = getSharedPreferences(prefName, MODE_PRIVATE).edit();
prefEdit.clear();
Map<String, ?> entries = (Map<String, ?>) input.readObject();
for (Entry<String, ?> entry : entries.entrySet()) {
Object v = entry.getValue();
String key = entry.getKey();
if (v instanceof Boolean)
prefEdit.putBoolean(key, ((Boolean) v).booleanValue());
else if (v instanceof Float)
prefEdit.putFloat(key, ((Float) v).floatValue());
else if (v instanceof Integer)
prefEdit.putInt(key, ((Integer) v).intValue());
else if (v instanceof Long)
prefEdit.putLong(key, ((Long) v).longValue());
else if (v instanceof String)
prefEdit.putString(key, ((String) v));
}
prefEdit.commit();
res = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}finally {
try {
if (input != null) {
input.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return res;
}
我希望我帮助别人,如果在这里的东西是错了,请告诉我。
I hope that I helped someone, and if something here is wrong please tell me.
埃拉德
这篇关于如何备份共享preferences到SD卡?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!