Java序列化示例

序列化是一种将对象以一连串的字节描述的过程,用于解决在对对象流进行读写操作时所引发的问题。那么什么情况下需要使用序列化呢?

1、需要通过网络来发送对象,或对象的状态需要被持久化到数据库或文件中。

2、序列化能实现深复制,即可以复制引用的对象。


package hanjia;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class People implements Serializable{
	
	private static final long serialVersionUID = 1L;
	
	public String name;
	public int age;
	
	public People(){
		this.name = "ali";
		this.age = 20;
	}

	public static void main(String[] args) {
		
		try {
			FileOutputStream fos = new FileOutputStream("people.out");
			ObjectOutputStream oop = new ObjectOutputStream(fos);
			oop.writeObject(new People());
			oop.close();
			
			FileInputStream fis = new FileInputStream("people.out");
			ObjectInputStream ois = new ObjectInputStream(fis);
			People p = (People)ois.readObject();
			ois.close();
			
			System.out.println(p.name);
			
		} catch (FileNotFoundException e) {
			System.out.println("ss");
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

}


你可能感兴趣的:(Java序列化示例)