learning java 实例序列化
对Person类实例进行序例化及反序例化:
Person.java
public class Person implements java.io.Serializable { private String name; private int age; // 注意此处没有提供无参数的构造器! public Person(String name, int age) { System.out.println("有参数的构造器"); this.name = name; this.age = age; } // 省略name与age的setter和getter方法 // name的setter和getter方法 public void 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(); } } }