安卓(Android) 怎么从文件加载SharedPreferences

2019年10月13日15:05:21安卓(Android) 怎么从文件加载SharedPreferences已关闭评论 334 1574字阅读5分14秒

1.简介

安卓(Android) 怎么从文件加载SharedPreferences?——请看下文。

2.示例代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

import java.io.IOException;
import java.io.ObjectInputStream;

import java.util.Map;
import java.util.Map.Entry;

import java.util.zip.GZIPInputStream;
import android.content.Context;

import android.content.SharedPreferences.Editor;

import android.preference.PreferenceManager;

public class Main {
    @SuppressWarnings("unchecked")
    static boolean loadSharedPreferencesFromFile(Context context, File src) {
        boolean res = false;
        ObjectInputStream input = null;
        try {
            GZIPInputStream inputGZIP = new GZIPInputStream(
                    new FileInputStream(src));
            input = new ObjectInputStream(inputGZIP);
            Editor prefEdit = PreferenceManager
                    .getDefaultSharedPreferences(context).edit();
            prefEdit.clear();
            Map<String, Object> entries = (Map<String, Object>) 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;
    }
}

 
继续阅读
编程十万个怎么办