import java.io.*; public class SerializationExample { public static void main(String[] args) { Person person = new Person("John", 30, "Male"); try { FileOutputStream fileOut = new FileOutputStream("person.ser"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(person); out.close(); fileOut.close(); } catch (IOException e) { e.printStackTrace(); } try { FileInputStream fileIn = new FileInputStream("person.ser"); ObjectInputStream in = new ObjectInputStream(fileIn); Person serializedPerson = (Person) in.readObject(); in.close(); fileIn.close(); System.out.println(serializedPerson); e.printStackTrace(); } } } class Person implements Serializable { private String name; private int age; private String gender; public Person(String name, int age, String gender) { this.name = name; this.age = age; this.gender = gender; } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + ", gender='" + gender + '\'' + '}'; } }


上一篇:
下一篇:
切换中文