Java Reference
In-Depth Information
// Write the john object first time to the stream
oos.writeObject(john);
System.out.println(john); // Display what we wrote
// Change john object's name and height
john.setName("John Jacobs");
john.setHeight(6.9);
// Write john object again with changed name and height
oos.writeObject(john);
System.out.println(john); // display what we wrote again
}
catch(IOException e1) {
e1.printStackTrace();
}
}
public static void deserialize(String fileName) {
// personmutable.ser file must exist in the current directory
File fileObject = new File(fileName);
try (ObjectInputStream ois =
new ObjectInputStream(new FileInputStream(fileObject))) {
// Read the two objects that were written in the serialize() method
MutablePerson john1 = (MutablePerson)ois.readObject();
MutablePerson john2 = (MutablePerson)ois.readObject();
// Display the objects
System.out.println("Objects are read from " +
fileObject.getAbsolutePath());
System.out.println(john1);
System.out.println(john2);
}
catch(IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Objects are written to C:\book\javabook\mutableperson.ser
Name: John, Gender: Male, Height: 6.7
Name: John Jacobs, Gender: Male, Height: 6.9
--------------------------------------
Objects are read from C:\book\javabook\mutableperson.ser
Name: John, Gender: Male, Height: 6.7
Name: John, Gender: Male, Height: 6.7
Search WWH ::




Custom Search