如何在特定文件夹中存储SharedPreferences并获取它?

时间:2017-12-26 12:45:11

标签: android sharedpreferences storage

这是我在sharedPreferences中存储值的代码

SharedPreferences.Editor editor = context.getSharedPreferences("My_Table_name", Context.MODE_PRIVATE).edit();
    editor.putString("my_key", "how Are You Bro...");
    editor.apply();
    editor.commit();

我希望像这样保存它

File file = new File(Environment.getExternalStorageDirectory()+ "/.System/My_Table_Name");

    SharedPreferences.Editor editor = context.getSharedPreferences(file, Context.MODE_PRIVATE).edit();
    editor.putString("My_Key", "how Are You Bro...");
    editor.apply();
    editor.commit();

我该怎么做?

 getSharedPreferences(File file, int mode);

此方法可用,但已被删除。之前我曾尝试复制此文件,但对于此方法,该应用程序需要超级用户权限(root设备)。

我应该使用什么?

1 个答案:

答案 0 :(得分:0)

这个答案不是我的,我只是提供帮助。

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

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