import java.io.*; public class SerializableEmployee implements Serializable { String name; int age; double salary; SerializableEmployee(String name, int age, double salary) { this.name = name; this.age = age; this.salary = salary; } public void showDetails() { System.out.println("Name : " + name); System.out.println("Age : " + age); System.out.println("Salary : " + salary); } } class ObjectSerializationDemo { void writeData() { SerializableEmployee db[] = { new SerializableEmployee("Tom", 25, 1200.25), new SerializableEmployee("Dick", 22, 1223.25), new SerializableEmployee("Harry", 25, 1345.25) }; try { FileOutputStream out = new FileOutputStream("c://employee.txt"); try { ObjectOutputStream sout = new ObjectOutputStream(out); for (int i = 0; i < db.length; i++) { sout.writeObject(db[i]); } sout.close(); } catch (Exception e) { e.printStackTrace(); } } void readData() { try { FileInputStream in = new FileInputStream("c://employee.txt"); try { ObjectInputStream sin = new ObjectInputStream(in); try { SerializableEmployee se = (SerializableEmployee) sin .readObject(); se.showDetails(); se = (SerializableEmployee) sin.readObject(); se.showDetails(); se = (SerializableEmployee) sin.readObject(); se.showDetails(); sin.close(); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { ObjectSerializationDemo impl = new ObjectSerializationDemo(); impl.writeData(); impl.readData(); } }
Thursday, 2 June 2011
How to do object Serialization
Labels:
Java
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment