Saving objects to file

6 November 2007

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.

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

del.icio.us:Saving objects to file  digg:Saving objects to file  spurl:Saving objects to file  wists:Saving objects to file  simpy:Saving objects to file  newsvine:Saving objects to file  blinklist:Saving objects to file  furl:Saving objects to file  reddit:Saving objects to file  fark:Saving objects to file  blogmarks:Saving objects to file  Y!:Saving objects to file  smarking:Saving objects to file  magnolia:Saving objects to file  segnalo:Saving objects to file  gifttagging:Saving objects to file

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

Leave a Reply