View RSS Feed

My Java Tips

Saving objects to file

Rate this Entry
by , 11-10-2011 at 04:39 PM (746 Views)
Sometimes 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.

Java Code:
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.

Java Code:
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

Submit "Saving objects to file" to Facebook Submit "Saving objects to file" to Digg Submit "Saving objects to file" to del.icio.us Submit "Saving objects to file" to StumbleUpon Submit "Saving objects to file" to Google

Comments