[Core Java] Serialization & Deserialization
Objects can be flattened and inflated. Objects have state and behavior. Behaviour lies in the class but state lives in each individual object. So what happens when its time to save the state of an object? If you are writing a game, you would need a Save & Restore Game feature. Luckily there is a feature built in java which is to simply freeze-dry/ flatten / persist / dehydrate the object itself to save the state and reconstitute / inflate / restore / rehydrate to get it back.
You have lots of options for how to save the state of your Java Program, and what you will choose will probably depend on how you plan to use the saved state. Here are the options we will be looking at in this chapter.
If your data will be used by only the Java
program that generated it:
Use serialization
Write a file that holds flattened (serialized)
objects. Then have your program read the
serialized objects from the file and inflate them
back into living, breathing, heap-inhabiting objects.
If your data will be used by other programs:
Write a plain text file
Write a file, with delimiters that other programs can parse.
For example, a tab-delimited file that a spreadsheet or
database application can use. Saving State
1. Option One:
Write the three serialized character objects to a file
Create a file and write three serialized character objects. The file won’t make sense if you try to read it as text.
Create a file and write three serialized character objects. The file won’t make sense if you try to read it as text.
2. Option Two:
Write a plain text file
Create a file and write three lines of text,
one per character, separating the pieces
of state with commas:
50, Elf, bow, sword, dust
200, Troll, bare hands, big ax
120, Magician, spells, invisibility
50, Elf, bow, sword, dust
200, Troll, bare hands, big ax
120, Magician, spells, invisibility
Write a serialized object to a File
Following are the steps to create a seriliazed object:
1. Make a FileOutputStream
FileOutputStream fileStream = new FileOutputStream(“MyGame.ser”);
2. Make an ObjectOutputStream
ObjectOutputStream os = new ObjectOutputStream(fileStream);
3. Write the object
os.writeObject(characterOne);
os.writeObject(characterTwo);
os.writeObject(characterThree);
4. Close the ObjectOutputStream
os.close();
Deserialization
FileOutputStream fileStream = new FileOutputStream(“MyGame.ser”);
2. Make an ObjectOutputStream
ObjectOutputStream os = new ObjectOutputStream(fileStream);
3. Write the object
os.writeObject(characterOne);
os.writeObject(characterTwo);
os.writeObject(characterThree);
4. Close the ObjectOutputStream
os.close();
Deserialization
Following picture explains how deserialization works:
Comments
Post a Comment