Java Reference
In-Depth Information
public void setHeight(double height) {
this.height = height;
}
public double getHeight() {
return height;
}
public String toString() {
return "Name: " + this.name + ", Gender: " + this.gender +
", Height: " + this.height ;
}
}
Listing 7-30. Writing an Object Multiple Times to the Same Output Stream
// MultipleSerialization.java
package com.jdojo.io;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class MultipleSerialization {
public static void main(String[] args) {
String fileName = "mutableperson.ser";
// Write the same object twice to the stream
serialize(fileName);
System.out.println("--------------------------------------");
// Read the two objects back
deserialize(fileName);
}
public static void serialize(String fileName) {
// Create a MutablePerson objects
MutablePerson john = new MutablePerson("John", "Male", 6.7);
File fileObject = new File(fileName);
try (ObjectOutputStream oos =
new ObjectOutputStream(new FileOutputStream(fileObject))) {
// Let's display the objects we have serialized on the console
System.out.println("Objects are written to " +
fileObject.getAbsolutePath());
Search WWH ::




Custom Search