package serializable;
import java.io.*;
public class Person implements Serializable {
??? private String name; ??? private String sex; ??? private int age;
??? public String getName() { ??????? return name; ??? }
??? public void setName(String name) { ??????? this.name = name; ??? }
??? public String getSex() { ??????? return sex; ??? }
??? public void setSex(String sex) { ??????? this.sex = sex; ??? }
??? public int getAge() { ??????? return age; ??? }
??? public void setAge(int age) { ??????? this.age = age; ??? }
??? //重写 equals方法(自定义对比方法) ??? public boolean equals(Person p) { ??????? //可以实现业务需要的相等条件 ??????? return this.name.equals(p.getName()); ??? }
??? public static void main(String[] args) { ??????? Person person = new Person(); ??????? person.setName("Young"); ??????? person.setSex("男"); ??????? person.setAge(25);
??????? try { ??????????? //写文件 ??????????? FileOutputStream fos = new FileOutputStream("p.ser");//项目跟目录 ??????????? ObjectOutputStream oos = new ObjectOutputStream(fos); ??????????? oos.writeObject(person); ??????????? oos.close(); ??????????? fos.close(); ??????????? //读文件 ??????????? FileInputStream fis = new FileInputStream("p.ser"); ??????????? ObjectInputStream ois = new ObjectInputStream(fis); ??????????? Person p = (Person) ois.readObject(); ??????????? ois.close(); ??????????? fis.close(); ??????????? System.out.println(p.getName()); ??????????? System.out.println(person.equals(p)); ??????? } catch (Exception ex) { ??????????? System.out.println(ex.getMessage()); ??????? } ??? } }