ObjectOutputStream—ObjectInputStream序列化和反序列化
Person
import java.io.Serializable;//起到标记作用 public class Person implements Serializable { private String name; private int age; @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + '}'; } public Person() { } public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
ObjectOutputStream
import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; public class Demo01ObjectOutputStream { public static void main(String[] args) throws IOException { ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("F:\\basic\\untitled13\\src\\it\\cast\\day15\\demo06\\1.txt")); oos.writeObject(new Person("美女",18)); oos.close(); } }
ObjectInputStream
import java.io.FileInputStream; import java.io.IOException; import java.io.ObjectInputStream; public class Demo02ObjectInputStream { public static void main(String[] args) throws IOException, ClassNotFoundException { ObjectInputStream ois=new ObjectInputStream(new FileInputStream("F:\\basic\\untitled13\\src\\it\\cast\\day15\\demo06\\1.txt")); Object object = ois.readObject(); ois.close(); System.out.println(object); Person p = (Person) object; System.out.println(p.getName()+"="+p.getAge()); } }