Java Reference
In-Depth Information
While the previous code fragment will work perfectly well, it does not result in a stream that is
particularly efficient since each output operation will write directly to the file. In practice you will
probably want to buffer write operations on the file in memory, in which case you would create the
ObjectOutputStream
object like this:
objectOut = new ObjectOutputStream(
new BufferedOutputStream(
new FileOutputStream(theFile)));
The
BufferedOutputStream
constructor creates an object that buffers the
OutputStream
object
that is passed to it, so here we get a buffered
FileOutputStream
object that we pass to the
ObjectOutputStream
constructor. With this arranged, each write operation to the
ObjectOutputStream
will write the
BufferedOutputStream
object. The
BufferedOutputStream
object will write the data to an internal buffer. Data from the buffer will be
written to the file whenever the buffer is full, or when the stream is closed by calling its
close()
method or flushed by calling its
flush
() method. By default the buffer has a capacity of 512 bytes. If
you want to use a buffer of a different size you can use the
BufferedOutputStream
constructor that
accepts a second argument of type
int
that defines the size of the buffer in bytes.
To write an object to the file
MyFile
, you call the
writeObject()
method for
objectOut
with a
reference to the object to be written as the argument. Since this method accepts a reference of type
Object
as an argument, you can pass a reference of any class type to the method. There are three basic
conditions that have to be met for an object to be written to a stream:
The class must be declared as
public
.
❑
The class must implement the
Serializable
interface.
❑
If the class has a direct or indirect base class that is not serializable, then that base class must
have a default constructor - that is, a constructor that requires no arguments. The derived
class must take care of transferring the base class data members to the stream.
❑
Implementing the
Serializable
interface is a lot less difficult than it sounds, and we will see how in
a moment. Later we will come back to the question of how to deal with a non-serializable base class.
If
myObject
is an instance of a public class that implements
Serializable
, then to write
myObject
to the stream that we defined above, you would use the statement:
try {
objectOut.writeObject(myObject);
} catch(IOException e) {
e.printStackTrace(System.err);
System.exit(1);
}