Write a java program that writes objects of Employee class in the file named emp.doc. Create Employee class as of you interest.

 import java.io.*;

class Employee implements Serializable {

private String name;

private int age;

public Employee(String name, int age) {

this.name = name;

this.age = age;

}

@Override

public String toString() {

return "Name:" + name + " Age:" + age;

}

}

class RWObject {

public static void main(String[] args) {

Employee employee1 = new Employee("Arjun", 20);

Employee employee2 = new Employee("Ram", 20);

try {

FileOutputStream fileOutputStream = new FileOutputStream("emp.doc");

ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);


//Write object to file

objectOutputStream.writeObject(employee1);

objectOutputStream.writeObject(employee2);

objectOutputStream.close();

fileOutputStream.close();

FileInputStream fileInputStream = new FileInputStream("emp.doc");

ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);


//Read Objects

Employee employee = (Employee) objectInputStream.readObject();

Employee employee3 = (Employee) objectInputStream.readObject();

System.out.println(employee.toString());

System.out.println(employee3.toString());

objectInputStream.close();

fileInputStream.close();

} catch (Exception e) {

e.printStackTrace();

}

}

}

Comments

Popular posts from this blog

What is RMI? Discuss stub and skeleton. Explain its role in creating distributed applications.

Short note on Uniform Gradient Cash Flow and PERT

Discuss classification or taxonomy of virtualization at different levels.