- Create an
Employeeclass (with attributes of your choice), - Serialize and write its objects to a file named
emp.doc.
✅ 1. Employee.java
import java.io.Serializable;
// Employee class with Serializable interface
public class Employee implements Serializable {
private int id;
private String name;
private double salary;
// Constructor
public Employee(int id, String name, double salary) {
this.id = id;
this.name = name;
this.salary = salary;
}
// Getters (Optional: Add setters if needed)
public int getId() {
return id;
}
public String getName() {
return name;
}
public double getSalary() {
return salary;
}
// toString method for easy display
@Override
public String toString() {
return "Employee [ID=" + id + ", Name=" + name + ", Salary=" + salary + "]";
}
}
✅ 2. WriteEmployeeToFile.java
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class WriteEmployeeToFile {
public static void main(String[] args) {
// Create a few Employee objects
Employee emp1 = new Employee(101, "Alice", 50000);
Employee emp2 = new Employee(102, "Bob", 60000);
Employee emp3 = new Employee(103, "Charlie", 55000);
try {
// File name is emp.doc (you can change extension if needed)
FileOutputStream fileOut = new FileOutputStream("emp.doc");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
// Write employee objects
out.writeObject(emp1);
out.writeObject(emp2);
out.writeObject(emp3);
out.close();
fileOut.close();
System.out.println("Employee objects have been written to emp.doc");
} catch (IOException e) {
e.printStackTrace();
}
}
}
🔄 Optional: Reading Back (For Testing)
If you want to read back the objects to verify:
import java.io.FileInputStream;
import java.io.ObjectInputStream;
public class ReadEmployeeFromFile {
public static void main(String[] args) {
try {
FileInputStream fileIn = new FileInputStream("emp.doc");
ObjectInputStream in = new ObjectInputStream(fileIn);
Employee e1 = (Employee) in.readObject();
Employee e2 = (Employee) in.readObject();
Employee e3 = (Employee) in.readObject();
in.close();
fileIn.close();
System.out.println(e1);
System.out.println(e2);
System.out.println(e3);
} catch (Exception e) {
e.printStackTrace();
}
}
}
⚠ Notes:
- Make sure
Employeeclass implementsSerializable. - You can store objects in
ArrayList<Employee>and serialize the list instead if you're writing many employees at once.