import java.io.*;
class Employee implements Serializable {
private String name;
private int age;
private String department;
public Employee(String name, int age, String department) {
网页链接 = name;
网页链接 = age;
网页链接 = department;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getDepartment() {
return department;
}
}
public class Main {
public static void main(String[] args) {
// 創建Employee對象
Employee employee1 = new Employee("John Doe", 30, "IT");
Employee employee2 = new Employee("Jane Smith", 35, "HR");
Employee employee3 = new Employee("Mike Johnson", 40, "Finance");
// 使用對象輸出流將Employee對象寫入文件
try {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("employee.ser"));
oos.writeObject(employee1);
oos.writeObject(employee2);
oos.writeObject(employee3);
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("employee.ser"));
Employee readEmployee1 = (Employee) ois.readObject();
Employee readEmployee2 = (Employee) ois.readObject();
Employee readEmployee3 = (Employee) ois.readObject();
ois.close();
System.out.println("Employee 1: " + readEmployee1.getName() + ", " + readEmployee1.getAge() + ", " + readEmployee1.getDepartment()); 55 System.out.println("Employee 2: " + readEmployee2.getName() + ", " + readEmployee2.getAge() + ", " + readEmployee2.getDepartment()); 56 System.out.println("Employee 3: " + readEmployee3.getName() + ", " + readEmployee3.getAge() + ", " + readEmployee3.getDepartment());
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}