java IO 序列化和反序列化


1.對象的序列化和反序列化。

     對象的序列化就是將 Object 轉換成 byte 序列,反之叫反序列化。

2.序列化流(ObjectOutputStream):是過濾流。writerObject;

  反序列流(ObjectInputStream):  readObject;

3.序列化接口(Serializable):

    對象必須實現序列化接口,才能進行序列化,否則將會出現異常,這個接口沒有任何方法。只是一個標準


4.沒有實現序列化撥錯。

package cn.lanz.stream.ser;

import java.io.Serializable;

public class Student implements Serializable{
	private String stuno;
	private String stuname;
	private int stuage;
	public Student() {
		super();
	}
	public Student(String stuno, String stuname, int stuage) {
		super();
		this.stuno = stuno;
		this.stuname = stuname;
		this.stuage = stuage;
	}
	public String getStuno() {
		return stuno;
	}
	public void setStuno(String stuno) {
		this.stuno = stuno;
	}
	public String getStuname() {
		return stuname;
	}
	public void setStuname(String stuname) {
		this.stuname = stuname;
	}
	public int getStuage() {
		return stuage;
	}
	public void setStuage(int stuage) {
		this.stuage = stuage;
	}
	@Override
	public String toString() {
		return "Student [stuno=" + stuno + ", stuname=" + stuname + ", stuage="
				+ stuage + "]";
	}
	
}

package cn.lanz.stream.ser;

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 ObjectSerialize {
	public static void main(String[] args) throws IOException, IOException, Exception {
		
		String file="demo/obj.dat";
		//序列化
		/*ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream(file));
		
		Student st=new Student("1001", "zhangsna", 20);
		oos.writeObject(st);
		oos.flush();
		oos.close();*/
		
		//反序列化
		ObjectInputStream ois=new ObjectInputStream(new FileInputStream(file));
		Student st=(Student) ois.readObject();
		System.out.println(st);
		ois.close();
	}
}

5.private transient int stuage;//不會進行jvm默認的序列化,但也可以自己完成序列化

private void writeObject(java.io.ObjectOutputStream s) throws IOException{
		s.defaultWriteObject();//JVM默認序列化的元素進行序列化。
		s.writeInt(stuage);//自己完成序列化
	}
反序列化
private void readObject(ObjectInputStream s) throws ClassNotFoundException, IOException{
		s.defaultReadObject();//JVM默認序列化的元素進行反序列化。
		this.stuage=s.readInt();//自己完成反序列化
	}


發佈了88 篇原創文章 · 獲贊 1 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章