Saving Objects
Chapter XIV of Head First Java Book
Imagine your playing a video game now. You want to stop and save it. So how does java manage this situation? Okay, let’s talk about it. We can save the object’s state and behaviors into the instance variable and save it. But it’s not practical. We can handle this situation easily using the OO way.
Saving State
There are two scenarios we can use to save the state.
01. Write the three serialized character objects to a file
02.Write a plain text file
Write a serialized object to a file
There are three steps
1. Make a FileOutputStream
FileOutputStream fileStream = new FileOutputStream(“MyGame.ser”);2. Make a ObjectOutputStream
ObjectOutputStream os = new ObjectOutputStream(fileStream);3. Write the object
Write them to a file MyGame.exe
os.writeObject(characterOne);
os.writeObject(characterTwo);
os.writeObject(characterThree);4. Close the objectOutputStram
Os.close();Java I/O API has connection streams. It represents connections to destinations and sources such as files or network sockets.
After the serialized process, objects save the values of the instance variables, but they can bring back to the hap again.
| When an object is serialized, all the objects it refers to from instance variables are also serialized. And all the objects those objects refer to are serialized. And all the objects referred to are serialized, and the best part is, it happens automatically.
Example for a serializable
import java.io.*;public class Box implements Serializable { private int width; private int height; public void setWidth(int w) { width = w; } public void setHeight(int h) { height = h; } public static void main (String[] args) { Box myBox = new Box();
myBox.setWidth(50);
myBox.setHeight(20); try {
FileOutputStream fs = new FileOutputStream(“foo.ser”);
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(myBox);
os.close(); } catch(Exception ex) { ex.printStackTrace(); } }}
- · You can skip some instance variables from serializable process. Using “transient” keyword.
class Chat implements Serializable {transient String currentID;
String userName;
// more code}
Deserialization: restoring an object
The process of restoring objects to their original state. There are 5 steps
1. Make a FileInputStream
FileInputStream fileStream = new FileInputStream(“MyGame.ser”);2. Make an ObjectInputStream
ObjectInputStream os = new ObjectInputStream(fileStream);3. Read the object
Object one = os.readObject();
Object two = os.readObject();
Object three = os.readObject();4. Cast the objects
Get Maneesh De Herath’s stories in your inbox
Join Medium for free to get updates from this writer.
Cast the objects
GameCharacter elf = (GameCharacter) one;
GameCharacter troll = (GameCharacter) two;
GameCharacter magician = (GameCharacter) three;5. Close the ObjectInputStream
os.close();When running the deserialization process, JVM will return all objects to the heap area and assign their values.
Bullet points
- You can save an object’s state by serializing the object.
- To serialize an object, you need an ObjectOutputStream (from the java.io package)
- Streams are either connection streams or chain streams.
- Connection streams can represent a connection to a source or destination, typically a file, network socket connection, or console.
- Chain streams cannot connect to a source or destination and must be chained to a connection (or other) stream.
- To serialize an object, call writeObject(theObject) on the ObjectOutputStream. You do not need to call methods on the FileOutputStream
- To be serialized, an object must implement the Serializable interface. If a superclass of the class implements Serializable, the subclass will automatically be serializable even if it does not specifically declare it implements Serializable.
- If any object in the graph is not serializable, an exception will be thrown at runtime unless the instance variable referring to the object is skipped.
- Mark an instance variable with the transient keyword if you want serialization to skip that variable. The variable will be restored as null (for object references) or default values (for primitives).
- During deserialization, the class of all objects in the graph must be available to the JVM.
- You read objects (using readObject()) in the order in which they were originally written.
- The return type of readObject() is type Object, so deserialized objects must be cast to their real type.
- Static variables are not serialized! It doesn’t make sense to save a static variable value as part of a specific object’s state since all objects of that type share only a single value — the one in the class.
Write String into a text file
The easiest way of data saving and restoring is serialization. However, sometimes you need to use a text file because If your application data use another application(not a java program). This is also a similar scenario to serialization in this you write String instead of objects. We use FileWriter instead of a FileOutputStream.
Lets consider below code
import java.io.*;class WriteAFile { public static void main (String[] args) { try {
FileWriter writer = new FileWriter(“Foo.txt”);
writer.write(“hello foo!”);
writer.close(); } catch(IOException ex) {
ex.printStackTrace(); } }}
Reading from a text file
We use FileReader to do reading and we use BufferredReader to make the reading more efficient. We use while loop to read file when readLine() is null we consider file has read completely.
import java.io.*;class ReadAFile {
public static void main (String[] args) { try {
File myFile = new File(“MyText.txt”);
FileReader fileReader = new FileReader(myFile);
BufferedReader reader = new BufferedReader(fileReader); String line = null; while ((line = reader.readLine()) != null) { System.out.println(line); } reader.close(); } catch(Exception ex) { ex.printStackTrace(); } }}
Bullet Points
- To write a text file, start with a FileWriter connection stream.
- Chain the FileWriter to a BufferedWriter for efficiency.
- A File object represents a file at a particular path but does not represent the actual contents of the file.
- With a File object, you can create, traverse, and delete directories.
- Most streams that can use a String filename can use a File object as well, and a File object can be safer to use.
- To read a text file, start with a FileReader connection stream.
- Chain the FileReader to a BufferedReader for efficiency.
- To parse a text file, you need to be sure the file is written in some way to recognize the different elements. A common approach is to use some kind of character to separate the individual pieces.
References
Head First Java Book 2nd Edition








