IO流之序列化流

/**
 *  序列化:把對象按照流一樣的方式存入文本文件或者在網絡中傳輸!
 * 	序列化流: 將對象-->文件/網絡
 *  反序列化流: 將文件/網絡 --> 對象 
 * @author wzj
 * @ClassName ObjectStreamDemo
 * @Date 2020年2月17日 上午9:58:42	
 *
 */
public class ObjectStreamDemo {

	public static void main(String[] args)throws Exception {
		
//		write();//序列化
		read(); //反序列化
	}

	private static void read()throws Exception{
		//創建反序列化對象
		ObjectInputStream ois = new ObjectInputStream(new FileInputStream("oos.txt"));
		Object obj = ois.readObject();
		ois.close();
		System.out.println(obj);
	}

	private static void write()throws IOException {
		//創建序列化對象
		ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("oos.txt"));
		oos.writeObject(new Student("wzj", 22));
		oos.close();
	}
}
/**
 * 類通過實現Serializable接口纔可以啓動序列化功能
 * Serializable是一個標記接口
 * 
 * java.io.InvalidClassException:是沒有生成序列化值
 * 生成了序列化值後,我們對類進行任何修改,它讀取以前的數據都是沒有問題的!
 * 
 * 注意:我一個類中可能有多個成員屬性,有些屬性我不想序列化,該怎麼辦?
 *     用 transient 修飾不想序列化的成員屬性即可!
 * @author wzj
 * @ClassName Student
 * @Date 2020年2月17日 上午10:03:19	
 *
 */
public class Student implements Serializable{
	
	private static final long serialVersionUID = -5806700070317353843L;
	
	private transient String name;
	private int age;
	
	public Student() {
		super();
	}
	
	public Student(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}

	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;
	}
	@Override
	public String toString() {
		return "Student [name=" + name + ", age=" + age + "]";
	}
	
}

 

 

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