Java Program on Serialization

Free Java courses with 37 real-time projects - Learn Java

Program 1

package dataflair;

import java.io.Serializable;

public class Student implements Serializable
{
    int rno;
    String name;
    int age;

    public Student(int rno, String name, int age) 
    {
        this.rno = rno;
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" + "rno=" + rno + ", name=" + name + ", age=" + age + '}';
    }
}

Program 2

package dataflair;
import java.io.*;
public class TestWriteObject 
{
       public static void main(String[] args) throws IOException
       {
           File F=new File("d://dataflair/studentdata.txt");
           FileOutputStream fos=null;
           ObjectOutputStream oos=null;
           try
           {
               fos=new FileOutputStream(F);
               oos=new ObjectOutputStream(fos);
               Student S=new Student(101,"Rajesh Sharma",23);
               fos.flush();
               oos.writeObject(S);
               System.out.println("Record Save..........");
           }
           finally
           {
               fos.close();
               oos.close();
           }    
       }
}

Program 3

package dataflair;
import java.io.*;
public class TestReadObject 
{
    public static void main(String[] args) throws IOException,ClassNotFoundException 
    {
        File F=new File("d://dataflair/studentdata.txt");
        if(F.isFile())
        {
            FileInputStream fis=null;
            ObjectInputStream ois=null;
           try
           {
                fis=new FileInputStream(F);
                ois=new ObjectInputStream(fis);
                Student S1;
                S1=(Student)ois.readObject();
                System.out.println(S1);
           }
           finally
           {
               fis.close();
               ois.close();
           }    
        }
        else
            System.out.println("file not found............");  
    }
    
}

 

Did you like our efforts? If Yes, please give DataFlair 5 Stars on Google

follow dataflair on YouTube

Leave a Reply

Your email address will not be published. Required fields are marked *