在Android开发中有时候我们会遇到要求存储一个对象或者是传输,这里讲解一个将对象转成Base64的字符串
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(**Object**);//这里的object是需要转化的对象
String str= Base64.encodeToString(bos.toByteArray(),
Base64.DEFAULT);
bos.close();
oos.close();
} catch (Exception e) {
MojiLog.e(this, "", e);
}
我们可以利用 SharedPreferences来存储这个字符串,当然当我们需要使用的时候我们可以重新解析
/**
* 此方法为获取本地存储的类
* @return
*/
Private StudentInfo getStudentInfo(String info ){
//获取本地存储的StudentInfo 类的二进制编码
StudentInfo Studentinfo= null;
if (!Util.isNull(info)) {
try {
byte[] gameByte = android.util.Base64.decode(info.getBytes(Charset.forName("UTF-8")),android.util.Base64.DEFAULT);
ByteArrayInputStream bis =
new ByteArrayInputStream(gameByte);
ObjectInputStream ois =
new ObjectInputStream(bis);
Studentinfo= (StudentInfo) ois.readObject();
bis.close();
ois.close();
} catch (Exception e) {
}
}
return Studentinfo;
}