1. 程式人生 > >java序列化小案例

java序列化小案例

1.建立一個需要序列化的類TestSerializ,要實現介面Serializable

package com.test;
import java.io.Serializable;

public class TestSerializ implements Serializable {
	private static final long serialVersionUID = 1897101177587682103L;

	private int id=100;
	private String name="ang";
	public int age=27;
	public String sex="男";
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
}

2.新建一個測試類TestExe,執行序列化和反序列化的過程

package com.test;

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

public class TestExe {

	public static void main(String[] args){
		try{
			TestExe te=new TestExe();
			te.testOut();
			te.testInput();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	//序列化
	public void testOut() throws IOException{
		FileOutputStream fos=new FileOutputStream("E:\\ang\\serializ.out");
		ObjectOutputStream objos=new ObjectOutputStream(fos);
		objos.writeObject(new TestSerializ());
		objos.close();
		fos.close();
	}
	//反序列化
	public void testInput() throws IOException, ClassNotFoundException{
		FileInputStream fis=new FileInputStream("E:\\ang\\serializ.out");
		ObjectInputStream objis=new ObjectInputStream(fis);
		TestSerializ ts=(TestSerializ)objis.readObject();
		System.out.println("id:"+ts.getId());
		System.out.println("name:"+ts.getName());
		System.out.println("age:"+ts.age);
		System.out.println("sex:"+ts.sex);
	}
}

3.執行結果如圖: