文章目录
- 1、简介
- 2、Serializable 序列化
1、简介
1)数据序列据话,就是将数据结构或者对象转化成可以存储或者传输的数据格式的过程。
2)序列话期间,数据结构或者对象将其数据保存带临时或者永久性的存储区。
3)反序列化过程,就是将生成的数据还原成数据结构或着对象。
2、Serializable 序列化
1)序列化对象到文件
主要代码
测试对象 UserTest
//将对象 序列化 保存到文件
private void GetObjectFromFile() {
try {
ObjectInputStream ois=new ObjectInputStream(new FileInputStream("/system/object.text"));
UserTest userTest = (UserTest)ois.readObject(); //读出对象
Log.i(TAG,"file to object name: " + userTest.getName());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//从文件 反序列化 获取对象
private void SavaObjectToFile(UserTest userTest) {
try {
//写对象流的对象
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("/system/object.text"));
oos.writeObject(userTest); //将对象p写入到oos中
oos.close(); //关闭文件流
Log.i(TAG,"Object write to file success");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
2)序列化对象到数据库
//将对象 转化成字节数据 从而可以保存到 数据库
public byte[] toByte(Object object) {
Log.d(TAG, “TypeChangeTool toByte()”);
byte[] data = null;
if(object != null){
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try {
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(object);
objectOutputStream.flush();
data = byteArrayOutputStream.toByteArray();
Log.d(TAG, “TypeChangeTool toByte() success”);
} catch (IOException e) {
Log.d(TAG, “TypeChangeTool toByte() throw exception=”+e.toString());
e.printStackTrace();
}
}
return data;
}//从数据库 获取字节数据 从而 转化成对象
public static Object toObject(byte[] data) {
Object object = null;
if(data != null && data.length > 0){
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data);
try {
ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
object = (Object)objectInputStream.readObject();
byteArrayInputStream.close();
objectInputStream.close();
Log.d(TAG, "TypeChangeTool toUserTags() success");
} catch (Exception e) {
Log.d(TAG, "TypeChangeTool toUserTags() throw exception="+e.toString());
e.printStackTrace();
}
}
return object;
}