Serialization Example Assignment Help

Assignment Help: >> IO Stream - Serialization Example

Serialization Example:

The given program describes how to use object serialization and deserialization. It starts through instantiating an object of class that is MyClass. This object has three object variables which are of types String, int and double. That is the information we need to save and restore.

A FileOutputStrem is created which refers to a file named "serial", and an ObjectOutputStream is created   for which file stream. A writeObject() method of ObjectOutputStream is then used to serialize our object. An object output stream is closed and flushed.

A FileInputStream is after that created which refers to the file named "serial", and an ObjectInputStream is created for that file stream.  A readObject () method of ObjectInputStream is then used to deserialize our object. The object input stream is after that closed.

Remember that MyClass is described to implement the Serializable interface. A NotSerializableException is thrown if this is not done. Try experimenting along with this program through declaring a few of the MyClass instance variables to be transient. That data is then not saved in during serialization.

Import java.io.*;

public class SerializationDemo{

public static void main( String args[]){|

//Object serialization try{

MyClass Object1 = new MyClass("Hello",-7,2.7e10);

System.out.println("object1: " +object1);

FileOutputStream fos = new FileOutputStream("serial");

objectOutputSteam oos = new ObjectOutputStream(fos);

oos.writeObject(object1);

oos.flush();

oos.close();

}

catch(Exception e) {

System.out.println("Exception during serialization:"+e);

System.exit(0);

}

//object deserialization

try{

MyClass object2;

FileInputStream fis = new FileInputStream("serial");

ObjectInputStream ois = new ObjectInputStream(fis);

Object 2 = (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 Serializabele{

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;

}

}

This above program describes in which the instance variables of object1 and object2 are identical. The output is display here:

Object 1: s=Hello; I=-7; d=2.7E10

Object2: s=Hello; I=-7; d=2 .7E10

Free Assignment Quote

Assured A++ Grade

Get guaranteed satisfaction & time on delivery in every assignment order you paid with us! We ensure premium quality solution document along with free turntin report!

All rights reserved! Copyrights ©2019-2020 ExpertsMind IT Educational Pvt Ltd