如何将 sharedpreferences 文件从内部存储传输到外部存储?

How to transfer sharedpreferences file from internal storage to external storage?

如何将 sharedpreferences 复制到外部存储以保持 xml format,以便以后可以共享首选项。

尝试读取 sharedpreferences 并另存为 string 文件,创建了 JSON 类型的 string,但我需要一个 xml。想过遍历app的内部存储,复制文件放到外部存储,但是那样太复杂了。

只是真的很想知道是否有一种简单而明智的方法来转移`sharedpreferences。

使用此代码,

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

注意您只能使用此代码处理字符串类型首选项,

要从文件加载共享首选项试试这个


private fun loadSharedPreferences(src: File, sharedPreferences : SharedPreferences) {
    try{
      var fileInput : FileInputStream = FileInputStream(src)
      val properties : Properties = Properties()
      properties.loadFromXML(fileInput)
      fileInput.close()
      val enuKeys = properties.keys()
      val editor = sharedPreferences.edit()
      while (enuKeys.hasMoreElements()){
        var key = enuKeys.nextElement() as String
        var value = properties.getProperty(key)
        when {
          key.contains("string",true) -> {    //in my case the key of a String contain "string"
            editor.putString(key, value)
          }
          key.contains("int", true) -> {    //in my case the key of a Int contain "int"
            editor.putInt(key, value.toInt())
          }
          key.contains("boolean", true) -> {  // //in my case the key of a Boolean contain "boolean"
            editor.putBoolean(key, value.toBoolean())
          }
        }

        editor.apply();
      }
    }catch ( e : FileNotFoundException) {
      e.printStackTrace();
    } catch ( e : IOException) {
      e.printStackTrace();
    }

  }