Java Reference
In-Depth Information
Create an object of the ObjectOutputStream class by using it as a decorator for another output stream that
represents the storage medium to save the object. For example, to save an object to a person.ser file, create an object
output stream as follows:
// Create an object output stream to write objects to a file
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("person.ser"));
To save an object to a ByteArrayOutputStream , you construct an object output stream as follows:
// Creates a byte array output stream to write data to
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// Creates an object output stream to write objects to the byte array output stream
ObjectOutputStream oos = new ObjectOutputStream(baos);
Use the writeObject() method of the ObjectOutputStream class to serialize the object by passing the object
reference as an argument, like so:
// Serializes the john object
oos.writeObject(john);
Finally, use the close() method to close the object output stream when you are done writing all objects to it:
// Close the object output stream
oos.close();
Listing 7-23 defines a Person class that implements the Serializable interface. The Person class contains three
fields: name , gender, and height . It overrides the toString() method and returns the Person description using the
three fields. I have not added getters and setters for the fields in the Person class to keep the class short and simple.
Listing 7-24 demonstrates how to write Person objects to a person.ser file. The output displays the objects written to
the file and the absolute path of the file, which may be different on your machine.
Listing 7-23. A Person Class That Implements the Serializable Interface
// Person.java
package com.jdojo.io;
import java.io.Serializable;
public class Person implements Serializable {
private String name = "Unknown";
private String gender = "Unknown" ;
private double height = Double.NaN;
public Person(String name, String gender, double height) {
this.name = name;
this.gender = gender;
this.height = height;
}
Search WWH ::




Custom Search