49) SERIALIZATION

PHOTO EMBED

Mon Jul 08 2024 13:19:26 GMT+0000 (Coordinated Universal Time)

Saved by @varuntej #java

Serialization program with 3 files

import java.io.*;

public class Student implements Serializable
{
	private int id;
	private String name;
	private double percentage;
	
	// use transient and static variables to check if they are saved
	
	public Student(int id, String name, double percentage)
	{
		this.id = id;
		this.name = name;
		this.percentage = percentage;
	}
	
	public String toString()
	{
		return "ID: "+this.id+", Name: "+this.name+", Percentage: "+this.percentage;
	}
}





import java.io.*;

public class SerializationDemo
{
	public static void main(String[] args)
	{
		try(FileOutputStream fos = new FileOutputStream("serial.txt");
		    ObjectOutputStream out = new ObjectOutputStream(fos);
		   )
		   {   System.out.println("Creating a student");
			   Student s = new Student(100, "John", 98.56);
			   System.out.println(s);
			   out.writeObject(s);
			   System.out.println("Object serialized");
		   }
		   catch(FileNotFoundException fe){ fe.printStackTrace();}
		   catch(IOException ie){ ie.printStackTrace(); }
	}
}

import java.io.*;

public class DeserializationDemo
{
	public static void main(String[] args)
	{
		try(FileInputStream fis = new FileInputStream("serial.txt");
		    ObjectInputStream in = new ObjectInputStream(fis);
		   )
		   {   System.out.println("Restoring the object");
			   Student s = (Student)in.readObject();
			   System.out.println(s);
			   System.out.println("Deserialization Done");
		   }
		   catch(ClassNotFoundException ce){ ce.printStackTrace();}
		   catch(IOException ie){ ie.printStackTrace(); }
	}
}
content_copyCOPY