import java.io.*;
public class SerializationExample {
public static void main(String[] args) {
Employee employee = new Employee("John Doe", "Software Engineer", 1000);
try {
FileOutputStream fileOut = new FileOutputStream("employee.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(employee);
out.close();
fileOut.close();
} catch (IOException e) {
e.printStackTrace();
}
Employee deserializedEmployee = null;
try {
FileInputStream fileIn = new FileInputStream("employee.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
deserializedEmployee = (Employee) in.readObject();
in.close();
fileIn.close();
} catch (IOException e) {
e.printStackTrace();
return;
} catch (ClassNotFoundException e) {
e.printStackTrace();
return;
}
System.out.println("Name: " + deserializedEmployee.getName());
System.out.println("Role: " + deserializedEmployee.getRole());
System.out.println("Salary: " + deserializedEmployee.getSalary());
}
}
class Employee implements Serializable {
private String name;
private String role;
private int salary;
public Employee(String name, String role, int salary) {
this.name = name;
this.role = role;
this.salary = salary;
}
public String getName() {
return name;
}
public String getRole() {
return role;
}
public int getSalary() {
return salary;
}
}