writing and reading data in file using objectInputstream and objectoutputstream in java with examples

Updated:06/feb/2022 by Computer Hope

Here we are creating object of objectoutputstream for writing file and for printing we use objectInputstream
Refer below code for more understanding

import java.io.*;
import java.util.*;
class Emp implements Serializable
{
	private int age;
	private String name;
	private double sal;
	
	public void get()
	{
		Scanner kb=new Scanner(System.in);
		System.out.println("enter age name and sal");
		age=kb.nextInt();
		name=kb.next();
		sal=kb.nextDouble();
	}
	public void show()
	{
		System.out.println(age);
		System.out.println(name);
		System.out.println(sal);
	}
	
}

class FileExample6
{
	public static void main(String args[]) 
{
    try
    {
    ObjectOutputStream oos;
    oos=new ObjectOutputStream(new FileOutputStream("D:/emp.dat"));
    Emp E=new Emp();
    E.get();
    oos.writeObject(E);
    oos.close();
    
    ObjectInputStream ios;
    ios=new ObjectInputStream(new FileInputStream("D:/emp.dat"));
    Emp F;
    F=(Emp)ios.readObject();
    F.show();
    ios.close();
    
    }
    catch(Exception ex)
    {
    	System.out.println("Error in writing or reading Object");
    }
}
}