【问题标题】:Saving sharedPreference file保存 sharedPreference 文件
【发布时间】:2014-02-13 15:54:18
【问题描述】:

我已成功将首选项保存在 SharedPreferences 中。如何将首选项文件保存在 sdcard 中,反之亦然??? {我想为用户提供备份选项,以便他可以在重新安装时保存和加载首选项}

【问题讨论】:

  • 您可以尝试从 /data/data/your.app.name/shared_prefs/your.app.name.preferences.xml 复制
  • 我想通过代码来实现,稍后为用户实现选项
  • 是的,当然,通过代码。我不是说手动。
  • 我的意思是建议一些复制方法...无论如何谢谢
  • 查看黑带的回答

标签: java android sharedpreferences


【解决方案1】:

要将 sharedpreference 存储在 sdcard 中,您可以尝试

  private void backup(Context context) {
  File root = context.getFilesDir();
    File parent = root.getParentFile();
    File[] files = parent.listFiles();
    File[] tmp = null;
    for (File file : files) {
        if (file.isDirectory()) {
            tmp = file.listFiles(new FileFilter() {
                @Override
                public boolean accept(File pathname) {
                    return pathname.getName().contains("your_shared_preference_file_name");
                }
            });
            if (tmp != null && tmp.length == 1) {
                break;
            }
        }
    }

    File file = null;
    if (tmp.length == 1) {
        parent = tmp[0].getParentFile();
        file = new File(Environment.getExternalStorageDirectory(), "tmp.xml");
        FileInputStream fis = new FileInputStream(tmp[0]);
        FileOutputStream fos = new FileOutputStream(file);
        byte[] buffer = new byte[32768];
        int count = 0;
        while ((count = fis.read(buffer)) > 0) {
            fos.write(buffer, 0, count);
        }
        fis.close();
        fos.flush();
        fos.close();
    } 

}

【讨论】:

    【解决方案2】:

    终于有时间完成项目了

    由于我使用了一个首选项文件来保存用户数据,因此这是我用来复制它的代码。

    File fileSrc = new File(filePath, "userdata.xml");
    File fileDes = new File("/data/data/com.nik/shared_prefs/", "userdata.xml");
    ...
    ...
    private void copyFileToShared(File fileSrc, File fileDes) {
    FileInputStream fileinputstream=null;
    FileOutputStream fileoutputstream=null;
    try {
    fileinputstream = new FileInputStream(fileSrc);
    fileoutputstream = new FileOutputStream(fileDes);
    byte[] buffer = new byte[4096];
    int count = 0;
    while ((count = fileinputstream.read(buffer)) > 0) {
        fileoutputstream.write(buffer, 0, count);
    }
    fileinputstream.close();
    fileoutputstream.flush();
    fileoutputstream.close();
    }
    catch(IOException e) {
        e.printStackTrace();
    }
    }
    

    文件被复制了... :-)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-12
      • 2016-03-27
      相关资源
      最近更新 更多