saving
objects
432
chapter 14
Here are the steps for serializing (saving) an object. Don’t bother
memorizing all this; we’ll go into more detail later in this chapter.
Writing a
serialized object to a file
FileOutputStream fileStream = new FileOutputStream(“MyGame.ser”);
Make a FileOutputStream object. FileOutputStream
knows how to connect to (and create) a file.
1
Make a FileOutputStream
os.writeObject(characterOne);
os.writeObject(characterTwo);
os.writeObject(characterThree);
3
Write the object
os.close();
4
Close the ObjectOutputStream
serializes the objects
referenced by character-
One, characterTwo, and characterThree, and
writes them to the file “MyGame.ser”.
Closing the stream
at the top closes the ones
underneath, so the FileOutputStream (and the
file) will close automatically.
If the file “MyGame.ser” doesn’t
exist, it will be created
automatically.
ObjectOutputStream os = new ObjectOutputStream(fileStream);
Do'stlaringiz bilan baham: