I am trying to build a program in Java involving serialization and deserialization. There are two classes, Employee and LauncherClass.
Employee.java:
import java.io.Serializable;
public class Employee implements Serializable {
String name;
int id;
int age;
double salary;
public Employee() {
this.name="";
this.id=0;
this.age=0;
this.salary=0.0;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setId(int id)
{
this.id = id;
}
public int getId()
{
return id;
}
public void setAge(int age)
{
this.age = age;
}
public int getAge()
{
return age;
}
public void setSalary(double salary) {
this.salary = salary;
}
public double getSalary()
{
return salary;
}
public String toString()
{
return id + " " + name + " " + age + " " + salary;
}
}
LauncherClass.java:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Scanner;
public class LauncherClass {
public static void main(String[] args) throws IOException, ClassNotFoundException {
Scanner sc = new Scanner(System.in);
Employee employee = new Employee();
FileOutputStream fileOutputStream = new FileOutputStream("datafile");
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
int choice;
do {
System.out.println("Main Menu");
System.out.println("1.Add an Employee");
System.out.println("2.Display All");
System.out.println("3.Exit");
choice = sc.nextInt();
switch(choice)
{
case 1:
System.out.print("Enter Employee ID:");
employee.setId(sc.nextInt());
sc.nextLine();
System.out.print("Enter Employee Name:");
employee.setName(sc.nextLine());
System.out.print("Enter Employee Age:");
employee.setAge(sc.nextInt());
System.out.print("Enter Employee Salary:");
employee.setSalary(sc.nextDouble());
objectOutputStream.writeObject(employee);
break;
case 2:
System.out.println("----Report----");
FileInputStream fileInputStream = new FileInputStream("datafile");
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
while(fileInputStream.available()>0)
{
employee = (Employee)objectInputStream.readObject();
System.out.println(employee);
}
System.out.println("----End of Report---");
objectInputStream.close();
break;
case 3:
System.exit(5);
}
} while (choice!=3);
objectOutputStream.flush();
objectOutputStream.close();
}
}
I execute this program and add some employees, then display the data of the object. Until this point, everything works fine. But when I exit and relaunch the program and select the display option, it shows nothing. Why is this so? Why is the data in the object being lost?