Saving the Objects in Java
Submitted by mehfuza on Friday, August 30, 2013 - 09:00.
Our programs reside on Hard Disk. Every program is brought into Main memory(RAM) for execution. Variables, Objects are runtime entity which means they are saved in RAM. Once you run the Program, variables, objects come into existence but once we close our program they are deleted from the Main Memory. In order to save the state(instance variable) of objects they must be saved on Secondary Memory(Hard Disk). Following are steps for serializing(saving) the objects.
Sterp 1: Implementing Seriazable Interface
In order to save the object in entirety we need the class to implement the Seriazable interface. Seraizable interface save the object in entirety or not at all. We can save the objects without implementing the Interface but the object may be partially saved, for example some instance variables may be saved and other not.
FileOutputStream can write bytes to file. If the file game.ser is not there, it will be created. Seriazable file(.ser) are much harder for human to understand but easier for the program. You can save the object to text file (.txt) also.
Step 3:Make an ObjectOutputStream
ObjectOutputStream lets us write the objects but can't directly connect to a file, so we require FileOutputStream which write the bytes to file.
Step4: Write the object
Step 4: Close the ObjectOutputStream
Closing the stream at the top class, the one underneath(FileOutputStream) will cloase automatically.
Put the above complete code in try{} block and catch the Exception, because I/O operations can through exceptions.
Note: If you don't want a particular instance variable to be saved declair it as transient.
Step 3: Read the objects
Each time we read the object, we get the next object, that's the reason you should save it in .ser file.
Step 4: Cast the Object.
Casting the objects to specific type of Class.
Step 5: Close the ObjectInputStream
Public class SavingObject implements Seriazable{}
Step 2: Make FileOutputStream
- objstrm.writeObject(obj);
- objstrm.close();
Deserializing the Objects:
Now we have saved the object to a file we can use them in our program. Following are steps to dese rialize the objects. Steps are similar to above steps. Step 1: Make FileIntputStream.FileInputStream fs=new FileInputStream(“game.ser”);
Step 2: Make an ObjectInputStream
- SavingObject newone=(SavingObject)one;
- SavingObject newtwo=(SavingObject)two;
obj.close();
This way we can save the state of objects and restore them later. This can be used for saving Game states, saving transaction ID, etc.Add new comment
- 28 views