package ObjectDemo;
import java.io.Serializable;
public class Person implements Serializable {
String name;
int age;
public Person(String name,int age){
this.name=name;
this.age=age;
}
}
序列化
package ObjectDemo;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
public class GameEnd {
public static void main(String[] args) throws FileNotFoundException, IOException {
Person[] p = {new Person("tom",11),new Person("jim",12),new Person("java",13)};
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("f:\\a.za"));
oos.writeObject(p);
oos.close();
}
}
反序列化
package ObjectDemo;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
public class GameStart {
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("f:\\a.za"));
Person[] p = (Person[]) ois.readObject();
for (Person per : p) {
System.out.println(per.name + " " + per.age);
}
ois.close();
}
}