import java.io.*; public class SerializationDemo { public static void main(String[] args) { Employee employee = new Employee("John Doe", "Software Engineer", 10000); String filePath = "employee.ser"; serializeObject(employee, filePath); Employee deserializedEmployee = (Employee) deserializeObject(filePath); System.out.println("Deserialized Employee:"); System.out.println("Name: " + deserializedEmployee.getName()); System.out.println("Designation: " + deserializedEmployee.getDesignation()); System.out.println("Salary: " + deserializedEmployee.getSalary()); } private static void serializeObject(Object object, String filePath) { try { FileOutputStream fileOut = new FileOutputStream(filePath); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(object); out.close(); fileOut.close(); System.out.println("Serialized data is saved in " + filePath); } catch (IOException e) { e.printStackTrace(); } } private static Object deserializeObject(String filePath) { Object object = null; try { FileInputStream fileIn = new FileInputStream(filePath); ObjectInputStream in = new ObjectInputStream(fileIn); object = in.readObject(); in.close(); fileIn.close(); e.printStackTrace(); } return object; } } class Employee implements Serializable { private static final long serialVersionUID = 1L; private String name; private String designation; private transient double salary; public Employee(String name, String designation, double salary) { this.name = name; this.designation = designation; this.salary = salary; } public String getName() { return name; } public String getDesignation() { return designation; } public double getSalary() { return salary; } }


上一篇:
下一篇:
切换中文