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
Post a Comment