1. 程式人生 > >Java基礎Demo -- IO 操作物件流

Java基礎Demo -- IO 操作物件流

ObjectInputStream和ObjectOutputStream的簡單運用

import java.io.*;

class MyClass implements Serializable
{
	private String name = "dindoa";
	private int age = 18;
	private char sex = 'm';
	private transient String grade = "student";

	public MyClass(String name, int age, char sex, String grade){
		this.name = name;
		this.age = age;
		this.sex = sex;
		this.grade = grade;
	}

	public String toString(){
		return "name:"+name+", age:"+age+", sex:"+sex + (null==grade?"":", grade:"+grade+"");
	}
}

public class SerializableDemo
{
	public static void main(String[] args) 
	{
		MyClass myObj = new MyClass("aaa",1,'m',"bbb");
		
		try( ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("serial"));
		     ObjectInputStream in = new ObjectInputStream(new FileInputStream("serial"))
		){
			out.writeObject(myObj);
			out.flush();

			MyClass readObj = (MyClass)in.readObject();

			//grade變數是transient修飾的,不會被序列化
			System.out.println(myObj);   //輸出name:aaa, age:1, sex:m, grade:bbb
			System.out.println(readObj); //輸出name:aaa, age:1, sex:m

		}catch(Exception e){}
	}
}