Advertisements
Home > Java > Java Program to handle object serialization using ObjectInputStream and ObjectOutputStream – Q43

Java Program to handle object serialization using ObjectInputStream and ObjectOutputStream – Q43


Q43: Java Program to handle object serialization using ObjectInputStream and ObjectOutputStream.

import java.io.*;

public class SerializationDemo{
	public static void main(String args[]){
		try{
			Myclass object1 = new Myclass("Hello", -7, 2.7e10);
			System.out.println("object1: " + object1);
			FileOutputStream fos = new FileOutputStream("serial");
			ObjectOutputStream oos = new ObjectOutputStream(fos);
			oos.writeObject(object1);
			oos.flush();
			oos.close();
		}
		catch(IOException e){
			System.out.println("Exception during serialization: " + e);
			System.exit(0);
			
		}
		try{
			Myclass object2;
			FileInputStream fis = new FileInputStream("serial");
			ObjectInputStream ois = new ObjectInputStream(fis);
			object2 = (Myclass)ois.readObject();
			ois.close();
			System.out.println("object2: " + object2);
		}
		catch(Exception e){
			System.out.println("Exception during Deserialization: " + e);
			System.exit(0);
		}
	}
}
class Myclass implements Serializable{
	String s;
	int i;
	double d;
	public Myclass(String s, int i, double d){
		this.s = s;
		this.i = i;
		this.d = d;
	}
	public String toString(){
		return "s= " + s + "; i= " + i + "; d= " + d;
	}
}

… from College notes (BCA/MCA assignments):


Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: