Java Reference
In-Depth Information
The
ObjectInput
and
ObjectOutput
interfaces extend the
DataInput
and
DataOutput
interfaces that
declare methods for reading and writing data of the primitive types and add the methods for reading and
writing objects. The
ObjectInputStream
class implements
ObjectInput
and
ObjectOutputStream
im-
plements
ObjectOutput
. Both object stream classes implement the
ObjectStreamConstants
interface,
which defines constants that are used to identify elements of an object in the stream. They both implement
the
AutoClosable
interface so they can be closed automatically if you create the objects within a
try
block
with resources.
WRITING AN OBJECT TO A FILE
To write objects to a file, the constructor for the
ObjectOutputStream
class requires a reference to an
Out-
putStream
object as an argument, and this object defines the stream that encapsulates the file in which you
intend to store your objects. You can create an
ObjectOutputStream
object from a channel with the follow-
ing statements:
Path file = Paths.get("MyObjectFile");
// Check out the file path...
// Create the object output stream for the file
try (ObjectOutputStream objectOut =
new ObjectOutputStream(Files.newOutputStream(file))){
// Write to the object output stream...
} catch(IOException e) {
e.printStackTrace();
}
I discussed the static
newOutputStream()
method that the
Files
class defines in Chapter 10. Here
you have not specified any open options so the default options assumed are
WRITE
,
CREATE
, and
TRUNCATE_EXISTING
. The
ObjectOutputStream
constructor throws an exception of type
IOException
if
an error occurs while the stream header is being written to the file.