Java 序列化
Java 提供了一种对象序列化的机制,该机制中,一个对象可以被表示为一个字节序列,该字节序列包括该对象的数据、有关对象的类型的信息和存储在对象中数据的类型。
将序列化对象写入文件之后,可以从文件中读取出来,并且对它进行反序列化,也就是说,对象的类型信息、对象的数据,还有对象中的数据类型可以用来在内存中新建对象。
整个过程都是 Java 虚拟机(JVM)独立的,也就是说,在一个平台上序列化的对象可以在另一个完全不同的平台上反序列化该对象。
类 ObjectInputStream 和 ObjectOutputStream 是高层次的数据流,它们包含反序列化和序列化对象的方法。
demo:
Employee e = new Employee();
e.name = "Reyan Ali";
e.address = "Phokka Kuan, Ambehta Peer";
e.SSN = 11122333;
e.number = 101;
【文件】序列化对象ObjectOutputStream
(当序列化一个对象到文件时, 按照 Java 的标准约定是给文件一个 .ser 扩展名。)
FileOutputStream fileOut = new FileOutputStream("/tmp/employee.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut.close();
demo2:
public static void main(String[] args) throws Exception {
AgencyVoInfo dept = new AgencyVoInfo();
dept.setAgencyCode("1");
dept.setAgencyName("2");
dept.setBranchCode("3");
dept.setId(1);
dept.setSerialNo(1);
String objectStr = serializeObject(dept);
System.out.println(objectStr);
AgencyVoInfo dept2 = (AgencyVoInfo)stringSerializeObject(objectStr);
System.out.println(JSON.toJSON(dept2));
}
【文件】反序列化对象ObjectInputStream
FileInputStream fileIn = new FileInputStream("/tmp/employee.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
e = (Employee) in.readObject();
in.close();
fileIn.close();
【字符串】对象序列化为字符串
public static String serializeObject(Object object)throws Exception{
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(byteArrayOutputStream);
out.writeObject(object);
//必须是ISO-8859-1
String objectStr = byteArrayOutputStream.toString("ISO-8859-1");
out.close();
byteArrayOutputStream.close();
return objectStr;
}
【字符串】字符串序列化为对象
public static Object stringSerializeObject(String objectStr)throws Exception{
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(objectStr.getBytes("ISO-8859-1"));
ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
Object object = objectInputStream.readObject();
objectInputStream.close();
byteArrayInputStream.close();
return object;
}