java - 将所有 SharedPreferences 导出和导入到文件

标签 java android sharedpreferences

在我的 Android 应用程序中,我在两个 SharedPreference 文件中有不同类型的数据( boolean 值、数字和字符串):com.package.indexcom.package.storage 。 问题是,如何将两个 SharedPreference 文件完全导出到外部文件并将其导入回来? (这对于设备之间的备份和迁移至关重要),谢谢

最佳答案

我就是这样做的:

private final SharedPreferences _settings;
/**
 * Serialize all preferences into an output stream
 * @param os OutputStream to write to
 * @return True iff successful
 */
public boolean serialize(final @NonNull OutputStream os) {
    ObjectOutputStream oos = null;
    try {
        oos = new ObjectOutputStream(os);
        oos.writeObject(_settings.getAll());
        oos.close();
    } catch (IOException e) {
        Log.e(TAG, "Error serializing preferences", BuildConfig.DEBUG ? e : null);
        return false;
    } finally {
        Utils.closeQuietly(oos, os);
    }
    return true;
}

/**
 * Read all preferences from an input stream.
 * Schedules a full preference clean, then deserializes the options present in the given stream.
 * If the given object contains an unknown class, the deserialization is aborted and the underlying
 * preferences are not changed by this method
 * @param is Input stream to load the preferences from
 * @return True iff the new values were successfully written to persistent storage
 *
 * @throws IllegalArgumentException
 */
public boolean deserialize(final @NonNull InputStream is) {
    ObjectInputStream ois = null;
    Map<String, Object> map = null;
    try {
        ois = new ObjectInputStream(is);
        map = (Map) ois.readObject();
    } catch (IOException | ClassNotFoundException e) {
        Log.e(TAG, "Error deserializing preferences", BuildConfig.DEBUG ? e : null);
        return false;
    } finally {
        Utils.closeQuietly(ois, is);
    }

    SharedPreferences.Editor editor = _settings.edit();
    editor.clear();

    for (Map.Entry<String, Object> e : map.entrySet()) {
        // Unfortunately, the editor only provides typed setters
        if (e.getValue() instanceof Boolean) {
            editor.putBoolean(e.getKey(), (Boolean)e.getValue());
        } else if (e.getValue() instanceof String) {
            editor.putString(e.getKey(), (String)e.getValue());
        } else if (e.getValue() instanceof Integer) {
            editor.putInt(e.getKey(), (int)e.getValue());
        } else if (e.getValue() instanceof Float) {
            editor.putFloat(e.getKey(), (float)e.getValue());
        } else if (e.getValue() instanceof Long) {
            editor.putLong(e.getKey(), (Long) e.getValue());
        } else if (e.getValue() instanceof Set) {
            editor.putStringSet(e.getKey(), (Set<String>) e.getValue());
        } else {
            throw new IllegalArgumentException("Type " + e.getValue().getClass().getName() + " is unknown");
        }
    }
    return editor.commit();
}

关于java - 将所有 SharedPreferences 导出和导入到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45552353/

相关文章:

java - 即使没有 gc 根,WebappClassLoader 内存泄漏

android - Dagger 2 - 构造函数注入(inject) - 非 Activity

Android 在共享首选项中存储用户 session

java - 使用 native 或内置函数生成多个随机数

java - Android HttpClient 异步任务

android - 当您可以使用静态变量执行相同的任务时,为什么要使用 parcelable?

java - android:将大字符串转换为字节并通过网络发送是否安全?

java - Android:应用程序不断预填充 sqlite 数据库

使用 Mockito 验证时来自 Kotlin 的 Java 泛型?

android - 如何将ListView滚动到底部?