保存sharedPreference文件

时间:2014-02-13 15:54:19

标签: java android sharedpreferences

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

2 个答案:

答案 0 :(得分:1)

要将共享偏好存储在SD卡中,您可以尝试

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

}

答案 1 :(得分:0)

终于有时间完成项目

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

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

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