Java序列化和反序列化

對象序列化(Serializable)是指將對象轉換爲字節序列的過程,而反序列化則是根據字節序列恢復對象的過程。 

序列化一般用於以下場景: 

1.永久性保存對象,保存對象的字節序列到本地文件中; 

2.通過序列化對象在網絡中傳遞對象; 

3.通過序列化在進程間傳遞對象。 

 一。編寫一個可以序列化的類

public class Dog implements Serializable{
	private int size;
	private String name;

	public Dog(int size, String name) {
		super();
		this.size = size;
		this.name = name;
	}
//geter setter
}
二。編寫測試類

package cn.edu.hpu.example;

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

public class SerializationDemo {
	public static void main(String[] args) throws IOException,
			ClassNotFoundException {
		   //序列化
		  FileOutputStream fos = new FileOutputStream("role.txt");
		  ObjectOutputStream os = new ObjectOutputStream(fos);
		  Dog d1 = new Dog(21, "lucky");
		  Dog d2 = new Dog(29, "lucky2"); 
		  Dog d3 = new Dog(19, "lucky3"); 
		  os.writeObject(d1); 
		  os.writeObject(d2);
		  os.writeObject(d3);
		  os.close();
		 
        /*
		//反序列化  字節轉換成對象
		FileInputStream fis = new FileInputStream("role.txt");
		ObjectInputStream is = new ObjectInputStream(fis);
		Object o1 = is.readObject();
		Object o2 = is.readObject();
		Object o3 = is.readObject();

		Dog d1 = (Dog) o1;
		Dog d2 = (Dog) o2;
		Dog d3 = (Dog) o3;
		System.out.println(d1.getName() + "," + d1.getSize());
		System.out.println(d2.getName() + "," + d2.getSize());
		System.out.println(d3.getName() + "," + d3.getSize());
		is.close();
		*/
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章