Total Pageviews

Search This Blog

Monday, March 28, 2011

How to Searialized Java Objects

package com.safiuz;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;

class Person implements Serializable {
String name;
int age;
Double weight;
public Person(String name, int age, Double weight){
this.name = name;
this.age= age;
this.weight = weight;
}

public String toString(){
return name+","+ age+","+ weight;
}

}

public class Manager{
public static void main(String[] args) {
Person p1 = new Person("abc",22,50.090);
File f1 = new File("text.txt");

FileOutputStream fout = null;
ObjectOutputStream out = null;

try{
fout = new FileOutputStream(f1);
out = new ObjectOutputStream(fout);
out.writeObject(p1);
System.out.println("done");
}
catch(IOException ex){
ex.printStackTrace();

}
finally
{
try
{
if(out!= null){
out.flush();
out.close();
out = null;
}
}
catch(IOException ex){
ex.printStackTrace();
}
try{
if (fout!= null){
fout.close();
fout=null;
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
}
}

No comments:

Post a Comment