對象序列化與反序列化

第一步:定義對象java

@SuppressWarnings("serial")
class Person implements Serializable{  //實現Serializable接口
	private String  name;
	private Integer age;
	private Double  height;
	public Person() {
		super();
	}
	public Person(String name, Integer age, Double height) {
		super();
		this.name = name;
		this.age = age;
		this.height = height;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	public Double getHeight() {
		return height;
	}
	public void setHeight(Double height) {
		this.height = height;
	}
	@Override
	public String toString() {
		return "Person [name=" + name + ", age=" + age + ", height=" + height + "]";
	}
	
}

第二步:進行序列化與反序列化操做ide

public class Ser {
     public static void main(String[] args) throws Exception{
    	 ser(new Person("高漸離",33,18.9));
    	 dser();
     }
     public static void ser(Object obj) throws Exception{
    	 FileOutputStream os = new FileOutputStream(new File("D:"+File.separator+"Person.ser"));
    	 // 要輸出一個對象,OutputStream只能是字節流,因此對象必須繼承Serializable接口
    	 ObjectOutputStream oos = new ObjectOutputStream(os);
    	 oos.writeObject(obj);   // 對象序列化
    	 oos.close();
     }
     public static void dser() throws Exception{
    	 FileInputStream is = new FileInputStream(new File("D:"+File.separator+"Person.ser"));
    	 ObjectInputStream ois = new ObjectInputStream(is);
    	 System.out.println(ois.readObject()); // 對象反序列化
    	 ois.close();
     }
}
相關文章
相關標籤/搜索