1. 程式人生 > >java 學習筆記---序列化

java 學習筆記---序列化

1.序列化

 

 

2.程式碼實操

Student 類:

package com.bond;

import java.io.Serializable;

public class Student  implements Serializable {
	private String sno;
	private String name;
	// transient 屬性使得 age屬性不能能被預設序列化
	private transient  int age; 
	private transient  String addr; 
		
	Student(){
		System.out.println("Student");
		
	}
	
	Student(String sno,String name,int age,String addr){
		this.sno=sno;
		this.name=name;
		this.age=age;
		this.addr=addr;
		
	}
	@Override
	public String toString() {
		return "Student [sno=" + sno + ", name=" + name + ", age=" + age + ",addr="+addr+"]";
	}
	
	public String getSno() {
		return sno;
	}
	public void setSno(String sno) {
		this.sno = sno;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	/**
	 * 自定義序列化屬性age
	 * @param s
	 * @throws java.io.IOException
	 */
	private void writeObject(java.io.ObjectOutputStream s)
	        throws java.io.IOException{
		   s.defaultWriteObject();
		   s.writeObject(addr);
		   s.writeInt(age);
		   
	}
	
	/**
	 * 自定義反序列化age
	 * @param s
	 * @throws java.io.IOException
	 * @throws ClassNotFoundException
	 */
	 private void readObject(java.io.ObjectInputStream s)
		        throws java.io.IOException, ClassNotFoundException {
	      s.defaultReadObject();// 預設把能序列化的屬性序列化 
	      this.addr=(String) s.readObject();
	      this.age=s.readInt();
	      
	      
	     
	 }
	
}

class Student1 extends Student {
	Student1(){
		System.out.println("Student1");
	}
}

 測試主類:

package com.bond;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class ObjectSeriDemo  {

	public static void main(String[] args) throws  Exception {
		// TODO Auto-generated method stub
		String objFile="D:\\javaio\\student.txt";
		Student st =new Student("10000","啊偉",25,"衚衕路1836號");
		Student1 st1 =new Student1();
		 
		//物件序列化
		ObjectOutputStream oos =new ObjectOutputStream(new FileOutputStream(objFile));
		//ObjectInputStream ios= new ObjectInputSteam(new ObjectInputStream());
 		oos.writeObject(st1);//序列化st1
		oos.flush();
		oos.close();
	  
		//反序列化
		System.out.println("*******");//反序列化分解符
		ObjectInputStream ios= new ObjectInputStream(new FileInputStream(objFile));
		Student1 stu=(Student1)ios.readObject();
		System.out.println(stu);
	}

}