如何将共享首选项
复制到保持xml格式
的外部存储,以便以后可以共享首选项。
尝试读取sharedpreferences
并将其作为string
保存到文件中,创建JSON
类型的string
,但我需要一个 xml
。想过遍历应用程序的内部存储并复制文件并将其放入外部存储中,但这可能太复杂。
只是真的想知道是否有一种简单而合理的方法来传输“共享首选项”。
最佳答案
使用此代码,
SharedPreferences preferences=this.getSharedPreferences("com.example.application", Context.MODE_PRIVATE);
Map<String,?> keys = preferences.getAll();
Properties properties = new Properties();
for(Map.Entry<String,?> entry : keys.entrySet()){
String key = entry.getKey();
String value = entry.getValue().toString();
properties.setProperty(key, value);
}
try {
File file = new File("externalPreferences.xml");
FileOutputStream fileOut = new FileOutputStream(file);
properties.storeToXML(fileOut, "External Preferences");
fileOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
并检索使用它,
try {
File file = new File("externalPreferences.xml");
FileInputStream fileInput = new FileInputStream(file);
Properties properties = new Properties();
properties.loadFromXML(fileInput);
fileInput.close();
Enumeration enuKeys = properties.keys();
SharedPreferences.Editor editor = preferences.edit();
while (enuKeys.hasMoreElements()) {
String key = (String) enuKeys.nextElement();
String value = properties.getProperty(key);
editor.putString(key, value);
editor.commit();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
注意您只能使用此代码处理字符串类型首选项,
关于java - 如何将共享首选项文件从内部存储传输到外部存储?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27917809/