Head First Java: Chapter-14 summary
Saving Objects
We need to save our object data to an external source. For that, we can use serialization or plain text file. The serialized file is much harder for humans to read. Still, it’s much easier (and safer) for your program to restore the three objects from serialization than from reading in the object’s variable values that were saved to a text file.
To Serialize an object, we need two classes that come with java.io package. They are OutputStream and ObjectOutputStream. Connection streams represent a connection to a source or destination (file, socket, etc.), while chain streams can’t connect independently and must be chained to a connection stream. The Connection streams are known as low-level. ObjectOutputStream (chained stream) and a Chained stream work if chained to other streams. But, It converts objects to data. Therefore we need to combine these objects to get a serialized object.
Writing a serialized object to a file
Step1: Make a FileOutputStream
Step2: Make an ObjectOutputStream
Step3: Write the object
Step4 Close the ObjectOutputStream
When we call the writeObject method, the object gets pumped to the stream, moves to the FileOutputStream and writes bytes to a file. We must implement that class with the Serializable interface to serialise an object. Then that class is eligible for serialization.
When an object is serialized, all the objects it refers to from instance variables are also serialized because instance variables are part of the object. Next, it will save the entire object graph. If we declare instance variables as “transient, “ that state value is not saved.
Deserialization
Deserialization is vice versa of serialization. It is used to take an object or object graph to the live.
Writing a String to a Text File
This is the same as serialization. In this, we are writing string into a text file.
Instead of using FileWrite, we can use the BufferedWriter. The writer will write something on the file when invoking the write method. Buffer Writer keeps things until their temporary memory is full.