Saving objects to file
6 November 2007Sometimes it is useful to store objects in files which can be read later. Object is saved along with its state. Simply saying, an object with its data can be saved in a file. Objects are made persistent this way.
The class whose object is to be saved should implements Serializable interface. We as a programmer are not supposed to add any method. The purpose of implementing interface is to tell the Java run time, which classes are to be serialized.
Serializable interface is part of java.io package. We will use FileOutputStream and ObjectOutputStream to write object to the file.
Now lets explore this with an example:
We have a class called TestsClass that implements Serializable interface. So we know that we can make objects of this class persistant.
import java.io.Serializable; public class TestClass implements Serializable{ private int age; private String name; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public void showAll(){ System.out.println("Name: " + name); System.out.println("Age: " + age); } }
Now lets create an object of TestClass and save it on disk.
TestClass obj = new TestClass(); obj.setAge(22); obj.setName("Dave"); FileOutputStream f_out = new FileOutputStream("C:\\myobject.data"); ObjectOutputStream obj_out = new ObjectOutputStream (f_out); obj_out.writeObject (obj);
We created an object of class TestClass, used setter methods to load data, and then saved it in a file called myobject.data using FileOutputStream and ObjectOutputStream objects.
Arrays, vectors, lists, and collections also implement Serializable interface which means that you can also make them persistent. So if you are using array, vector, list or collection in your program, and want to make it persistent on your disk, you just have to write few lines of code to make it persistent.
In the next post, I will write about retrieving serialized objects.
Happy coding
Related Posts:
Top Of Page | Trackback
If you found this page useful, consider linking to it. Simply copy and paste the code below into your web site.
It will look like this: Saving objects to file