简体   繁体   English

如何将SharedPreferences备份到SD卡?

[英]How can I backup SharedPreferences to SD card?

I saw in a lot of places that it's a problem to copy the SharedPreferences file to the sd card because every manufacturer place it somewhere else. 我在很多地方看到将SharedPreferences文件复制到SD卡是一个问题,因为每个制造商都将它放在其他地方。

I want to backup on the sd card no matter where is the file located. 无论文件位于何处,我都想在SD卡上备份。 Is there any way to do this? 有没有办法做到这一点?

The SharedPreferences interface contains a method called getAll() which returns a map with the key-value pairs. SharedPreferences接口包含一个名为getAll()的方法,该方法返回带有键值对的映射。 So instead of copying the file itself, I just serialize the map that being returned from this method and then retrieve it back afterwards. 因此,我只是序列化从此方法返回的映射,而不是复制文件本身,然后将其检索回来。

Some code: 一些代码:

private boolean saveSharedPreferencesToFile(File dst) {
    boolean res = false;
    ObjectOutputStream output = null;
    try {
        output = new ObjectOutputStream(new FileOutputStream(dst));
        SharedPreferences pref = 
                            getSharedPreferences(prefName, MODE_PRIVATE);
        output.writeObject(pref.getAll());

        res = true;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        try {
            if (output != null) {
                output.flush();
                output.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    return res;
}

@SuppressWarnings({ "unchecked" })
private boolean loadSharedPreferencesFromFile(File src) {
    boolean res = false;
    ObjectInputStream input = null;
    try {
        input = new ObjectInputStream(new FileInputStream(src));
            Editor prefEdit = getSharedPreferences(prefName, MODE_PRIVATE).edit();
            prefEdit.clear();
            Map<String, ?> entries = (Map<String, ?>) input.readObject();
            for (Entry<String, ?> entry : entries.entrySet()) {
                Object v = entry.getValue();
                String key = entry.getKey();

                if (v instanceof Boolean)
                    prefEdit.putBoolean(key, ((Boolean) v).booleanValue());
                else if (v instanceof Float)
                    prefEdit.putFloat(key, ((Float) v).floatValue());
                else if (v instanceof Integer)
                    prefEdit.putInt(key, ((Integer) v).intValue());
                else if (v instanceof Long)
                    prefEdit.putLong(key, ((Long) v).longValue());
                else if (v instanceof String)
                    prefEdit.putString(key, ((String) v));
            }
            prefEdit.commit();
        res = true;         
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }finally {
        try {
            if (input != null) {
                input.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    return res;
}

I hope that I helped someone, and if something here is wrong please tell me. 我希望我能帮助别人,如果有什么不对的地方请告诉我。

Elad 埃拉德

File ff = new File("/data/data/"
                            + MainActivity.this.getPackageName()
                            + "/shared_prefs/pref file name.xml");

                    Log.i("ddddddddddddd", ff.getPath() + "");

                    copyFile(ff.getPath().toString(), sdcard path/save file name.xml");

private void copyFile(String filepath, String storefilepath) {
    try {
        File f1 = new File(filepath);
        File f2 = new File(storefilepath);
        InputStream in = new FileInputStream(f1);

        OutputStream out = new FileOutputStream(f2);

        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        in.close();
        out.close();
        System.out.println("File copied.");
    } catch (FileNotFoundException ex) {
        System.out.println(ex.getMessage());

    } catch (IOException e) {
        System.out.println(e.getMessage());
    }

}

An alternative to using ObjectOutputStream/ObjectInputStream is to add the XmlUtils.java and FastXmlSerializer.java files from the Android source to your project, and then use XmlUtils.writeMapXml() and XmlUtils.readMapXml(): 使用ObjectOutputStream / ObjectInputStream的另一种方法是将Android源中的XmlUtils.java和FastXmlSerializer.java文件添加到项目中,然后使用XmlUtils.writeMapXml()和XmlUtils.readMapXml():

boolean res = false;
FileOutputStream output = null;
try {
    output = new FileOutputStream(dst);
    SharedPreferences pref = 
                        getSharedPreferences(prefName, MODE_PRIVATE);
    XmlUtils.writeMapXml(pref.getAll(), output);

    res = true;
    }

..... .....

FileInputStream input = null;
try {
    input = new FileInputStream(src);
        Editor prefEdit = getSharedPreferences(prefName, MODE_PRIVATE).edit();
        prefEdit.clear();
        Map<String, ?> entries = XmlUtils.readMapXml(input);
        for (Entry<String, ?> entry : entries.entrySet()) {
            putObject(prefEdit, entry.getKey(), entry.getValue());
        }
    }

..... .....

static SharedPreferences.Editor putObject(final SharedPreferences.Editor edit,
                                          final String key, final Object val) {
    if (val instanceof Boolean)
        return edit.putBoolean(key, ((Boolean)val).booleanValue());
    else if (val instanceof Float)
        return edit.putFloat(key, ((Float)val).floatValue());
    else if (val instanceof Integer)
        return edit.putInt(key, ((Integer)val).intValue());
    else if (val instanceof Long)
        return edit.putLong(key, ((Long)val).longValue());
    else if (val instanceof String)
        return edit.putString(key, ((String)val));

    return edit;
}

The storage format will then be the same XML as is used to store the SharedPreferences. 然后,存储格式将与用于存储SharedPreferences的XML相同。

try {
    input = new FileInputStream(src1);
    SharedPreferences.Editor prefEdit =   getSharedPreferences("prueba100", MODE_PRIVATE).edit();
    prefEdit.clear();
    Map<String, ?> entries = XmlUtils.readMapXml(input);
    for (Map.Entry<String, ?> entry : entries.entrySet()) {
        putObject(prefEdit, entry.getKey(), entry.getValue());
    }
    prefEdit.apply();
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (XmlPullParserException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM