Object Serialization and deserialization Examples

Before I was finishing off a blog post on object serialization, today saw something about the object serialization in a textbook, so wanted to write it down deeper impression

1. Object Object serialization is converted into a byte sequence, whereas the object is deserialized
    1) serialized stream (the ObjectOutputStream), a filtration flow
      ObjectOutputStream writeObject (Object) serialized object
      ObjectInputStream readObject () object is deserialized
    2) sequence of interfaces (serializable)
      object must implement the "serial interfaces" to be serialized, or can not serialize exception will appear!
      Serializable is an empty interface, there is no way, as only a serialized identifier
    3) javaBean specification, java class must implement the Serializable interface
      class in the API is in line with most java java Bean specification, basically realized Serializable
    4 ) serialization and de-objects can disguise a deep copy of an object that implements the
      
    case 1:
         

	public static void main(String[] args) throws Exception {
		String file ="F:/temp/obj.dat";
		//1.对象序列化
		FileOutputStream fos=new FileOutputStream(file);
		ObjectOutputStream out=new ObjectOutputStream(fos);
		
		Foo foo=new Foo();
		foo.setAge("12");
		foo.setSex("男");
		Foo f2=new Foo();
		f2.setAge("24");
		f2.setSex("女");
		out.writeObject(foo);//序列化,将对象写入到流中
		out.writeObject(f2);
		
		out.close();
		
		//2.对象的反序列化
		FileInputStream fis=new FileInputStream(file);
		ObjectInputStream in=new ObjectInputStream(fis);
		Foo f=(Foo) in.readObject();
		Foo ff=(Foo) in.readObject();
		System.out.println(f.getAge()+" ;;"+ff.getAge());
		//f是foo的深层复制
		System.out.println(f==foo);//false
		in.close();
	 }

 

2. Copy the shallow and deep copy *
    1) copy the Java default rule is shallow copy, good performance, but the isolation is poor. Phenomenon shallow copy, copy only the first layer of the object
    2) can be achieved using a deep copy serialization

Case 2:

public static Object deppClone(Object obj) throws Exception{
		try {
			//1.对象序列化
			//缓冲流:字节数组输出流
			ByteArrayOutputStream buf=new ByteArrayOutputStream();
			//对象输出流
			ObjectOutputStream out =new ObjectOutputStream(buf);
			out.writeObject(obj);//序列化对象到buf中
			out.close();
			
			//2.对象反序列化
			byte[]ary =buf.toByteArray();
			ByteArrayInputStream bais=new ByteArrayInputStream(ary);
			ObjectInputStream in=new ObjectInputStream(bais);
			Object o=in.readObject();//从ary反序列化
			in.close();
			return o;
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception();
		}
	}

 

Published 118 original articles · won praise 59 · views 490 000 +

Guess you like

Origin blog.csdn.net/u012255097/article/details/103951613