Sequence instances of the Person class of embodiments and embodiments of the reverse order:
Person.java
public class the Person the implements the java.io.Serializable { Private String name; Private int Age; // note here does not provide no-argument constructor! public the Person (String name, int Age) { System. OUT .println ( " there are parameters constructor " ); the this .name = name; the this .age = age; } // omitted name and age of the setter and getter methods // name setter and getter methods public void the setName (String name) { this.name = name; } public String getName() { return this.name; } // age的setter和getter方法 public void setAge(int age) { this.age = age; } public int getAge() { return this.age; } }
WriteObject:
import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; public class WriteObject { public static void main(String[] args) { try { var oos = new ObjectOutputStream(new FileOutputStream("object.txt")); var per = new Person("孙武空",500); oos.writeObject(per); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
ReadObject:
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.ObjectInputStream; public class ReadObject { public static void main(String[] args) throws FileNotFoundException { try { var ois = new ObjectInputStream(new FileInputStream("object.txt")); var p = (Person)ois.readObject(); System.out.println("name: " + p.getName() + " age : " + p.getAge()); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } }