import java.io.*;
import java.util.Date;
public class ObjectSaver {
public static void main(String[] args) throws Exception {
/*其中的 /Users/slq/Desktop/java/4/objectFile.obj 表示存放序列化對象的文件*/
//序列化對象
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("/Users/slq/Desktop/java/4/objectFile.obj"));
Customer customer = new Customer("王麻子", 24);
out.writeObject("你好!"); //寫入字面值常量
out.writeObject(new Date()); //寫入匿名Date對象
out.writeObject(customer); //寫入customer對象
out.close();
//反序列化對象
ObjectInputStream in = new ObjectInputStream(new FileInputStream("/Users/slq/Desktop/java/4/objectFile.obj"));
System.out.println("obj1 " + (String) in.readObject()); //讀取字面值常量
System.out.println("obj2 " + (Date) in.readObject()); //讀取匿名Date對象
Customer obj3 = (Customer) in.readObject(); //讀取customer對象
System.out.println("obj3 " + obj3);
in.close();
}
}
class Customer implements Serializable {
private String name;
private int age;
public Customer(String name, int age) {
this.name = name;
this.age = age;
}
public String toString() {
return "name=" + name + ", age=" + age;
}
}
java 泛型 序列化與反序列化實例
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.