---
title: "[转载]SharedPreferences 存储java对象，很实用"
author: "zhy20045923"
date: "2016-04-14T16:36:02Z"
tags: []
categories: ["移动开发"]
slug: "sharedpreferences-java"
draft: false
lastmod: "2016-04-14T16:36:02Z"
id: 2291297
url: "https://null-point.iteye.com/blog/2291297"
---

public void putObject(String key , Object obj){
                
                ByteArrayOutputStream bos = null;
                ObjectOutputStream oos = null;
                try {
                        bos = new ByteArrayOutputStream();
                        oos = new ObjectOutputStream(bos);
                        oos.writeObject(obj);
                        String serStr = bos.toString("ISO-8859-1");
                        serStr = URLEncoder.encode(serStr, "UTF-8");
                        editer.putString(key, serStr);
                        editer.commit();
                        
                } catch (IOException e) {
                        e.printStackTrace();
                }finally{
                        try {
                                oos.close();
                                bos.close();
                        } catch (IOException e) {
                                e.printStackTrace();
                        }
                }
        }
        
        public Object getObject(String key){
                
                String serStr = preferences.getString(key, "");
                ByteArrayInputStream bai = null;
                ObjectInputStream ois = null;
                Object object = null;
                if(serStr != ""){
                        
                        try {
                                String sedStr = URLDecoder.decode(serStr, "UTF-8");
                                bai = new ByteArrayInputStream(sedStr.getBytes("ISO-8859-1"));
                                ois = new ObjectInputStream(bai);
                                object = ois.readObject();
                                
                        } catch (Exception e) {
                                e.printStackTrace();
                        }finally{
                                try {
                                        ois.close();
                                        bai.close();
                                } catch (IOException e) {
                                        e.printStackTrace();
                                }
                        }
                }
                
                
                return object;
        }
序列化实体的话，别忘了 implements Serializable


原帖地址：
http://www.eoeandroid.com/thread-902119-1-6.html