使用SharePreference存储序列化对象

存储序列化对象

//创建字节输出流
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//创建字节对象输出流
ObjectOutputStream out = null;
try {
    //然后通过将字对象进行64转码,写入key值为key的sp中
    out = new ObjectOutputStream(baos);
    out.writeObject(需要存储的对象);
    String objectVal = new String(Base64.encode(baos.toByteArray(), Base64.DEFAULT));
    spCache.put(KEY, objectVal);
} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        if (baos != null) {
            baos.close();
        }
        if (out != null) {
            out.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

取出序列化对象

String json = spCache.get(KEY, "");
byte[] buffer = Base64.decode(json, Base64.DEFAULT);
//一样通过读取字节流,创建字节流输入流,写入对象并作强制转换
ByteArrayInputStream bais = new ByteArrayInputStream(buffer);
ObjectInputStream ois = null;
try {
    ois = new ObjectInputStream(bais);
    // 强转为指定对象
    views = (List<TextView>) ois.readObject();
} catch (IOException | ClassNotFoundException e) {
    e.printStackTrace();
} finally {
    try {
        if (bais != null) {
            bais.close();
        }
        if (ois != null) {
            ois.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

猜你喜欢

转载自blog.csdn.net/APTX8899/article/details/88674607