Wednesday, March 11, 2009

Simple java program to serialize an Object to a file

package test_project;

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;

public class testJava implements Serializable{

private int length;
private int width;

public testJava() {
length = 5;
width = 4 ;
}

public int getLength() {
return this.length;
}

public int getWidth() {
return this.width;
}

public static void main(String[] args) {
testJava testJava = new testJava();
try{
FileOutputStream fs = new FileOutputStream("C:\\my.ser");
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(testJava);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

Read this to deserialize the object from flat file

No comments: