Person实现序列化接口
public class Person implements Serializable {
int age = 8;
int score = 100;
@Override
public String toString() {
return "Person{" +
"age=" + age +
", score=" + score +
'}';
}
}
public static void save() {
File f = new File("d:/person.txt");
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(
new FileOutputStream(f));
oos.writeObject(new Person());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (oos != null) {
try {
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void load() {
File file = new File("d:/person.txt");
Person p = null;
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) {
p = (Person) ois.readObject();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
System.out.println(p);
}