将可以序列化的对象通过base64编码后进行保存
但是感觉多数情况下,不需要采用这个功能,直接保存原始的json字符串,取出来之后再进行解析即可
package com.wotlab.home.moneyplantairs.utils; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.StreamCorruptedException; import java.util.ArrayList; import java.util.HashMap; import android.annotation.SuppressLint; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.util.Base64; public class FileManager { /** * 将由网络获取的0点开始的等级数据封装成的ArrayTypeMap对象保存到sp文件中 * * @param arrayMap * @param sp * @throws IOException */ @SuppressLint("NewApi") public static void saveInfo(ArrayMapType arrayMap, SharedPreferences sp, String key) throws IOException { // 这个需要将请求到的数据保存到sp文件当中 ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream os = new ObjectOutputStream(bos); os.writeObject(arrayMap); // 编码是将字符数组编码为字符串 String stringBase64 = new String(Base64.encodeToString( bos.toByteArray(), Base64.DEFAULT)); Editor editor = sp.edit(); editor.putString(key, stringBase64); editor.commit(); } @SuppressLint("NewApi") /** * 从sp文件中读取信息,返回ArrayList<HashMap<String,String>>类型的数据 * @param sp sp文件 * @param key sp文件中存储对象的key值 * @return * @throws StreamCorruptedException * @throws IOException * @throws ClassNotFoundException */ public static ArrayList<HashMap<String, String>> readInfo( SharedPreferences sp, String key) throws StreamCorruptedException, IOException, ClassNotFoundException { String stringBase64 = sp.getString(key, null); // 进行对应的解码, byte[] bytesBase64 = Base64.decode(stringBase64.getBytes(), Base64.DEFAULT); ByteArrayInputStream bais = new ByteArrayInputStream(bytesBase64); ObjectInputStream ois = new ObjectInputStream(bais); ArrayMapType arrayMap = (ArrayMapType) ois.readObject(); return arrayMap.list; } }