public class Person implements java.io.Serializable { private String name; private int age; // Note that no parameterless constructor is provided here! public Person(String name , int age) { System.out.println("Constructor with parameters"); this.name = name; this.age = age; } // Omit the setter and getter methods of name and age // setter and getter methods for name public void setName(String name) { this.name = name; } public String getName() { return this.name; } // age's setter and getter methods public void setAge(int age) { this.age = age; } public int getAge() { return this.age; } }
import java.io. *; public class WriteObject { public static void main(String[] args) { try( // Create an ObjectOutputStream output stream ObjectOutputStream oos = new ObjectOutputStream( new FileOutputStream("object.txt"))) { Person per = new Person("Monkey King", 500); // write the per object to the output stream oos.writeObject (per); } catch (IOException ex) { ex.printStackTrace(); } } }
import java.io. *; public class ReadObject { public static void main(String[] args) { try( // Create an ObjectInputStream input stream ObjectInputStream ois = new ObjectInputStream( new FileInputStream("object.txt"))) { // Read a Java object from the input stream and cast it to the Person class Person p = (Person)ois.readObject(); System.out.println("Name is: " + p.getName() + "\nAge is: " + p.getAge()); } catch (Exception ex) { ex.printStackTrace(); } } }
import java.io. *; public class SerializeMutable { public static void main(String[] args) { try( // Create an ObjectOutputStream input stream ObjectOutputStream oos = new ObjectOutputStream( new FileOutputStream("mutable.txt")); // Create an ObjectInputStream input stream ObjectInputStream ois = new ObjectInputStream( new FileInputStream("mutable.txt"))) { Person per = new Person("Monkey King", 500); // The system will per object convert the byte sequence and output oos.writeObject (per); // Change the name instance variable of the per object per.setName("Pig Bajie"); // The system only outputs the serialization number, so the changed name will not be serialized oos.writeObject (per); Person p1 = (Person)ois.readObject(); //① Person p2 = (Person)ois.readObject(); //② // The following outputs true, that is, p1 is equal to p2 after deserialization System.out.println(p1 == p2); // The output "Monkey King" is still seen below, that is, the changed instance variable is not serialized System.out.println(p2.getName()); } catch (Exception ex) { ex.printStackTrace(); } } }