Java Tutorial
import java.io.*; //Class can be serialized class Employee implements Serializable { String name; int id; double salary; public Employee(String name, int id, double salary) { this.name = name; this.id = id; this.salary = salary; } public String toString() { return "name=" + name + "; id=" + id + "; salary=" + salary; } } public class SerializationTest { public static void main(String args[]) { //Serialization of object try { Employee obj = new Employee("Employee1", 1002, 5600.50); System.out.println("Employee Object:" + obj); FileOutputStream fout = new FileOutputStream("serial.txt"); ObjectOutputStream oout = new ObjectOutputStream(fout); oout.writeObject(obj); oout.flush(); oout.close(); } catch(Exception ex) { System.out.println("Error: " + ex.toString()); } } }Output:
$ javac SerializationTest.java $ java SerializationTest Employee Object:name=Employee1; id=1002; salary=5600.5 and also serial.txt file is created with encrypted format of object data.
import java.io.*; class Employee implements Serializable { String name; int id; double salary; public Employee(String name, int id, double salary) { this.name = name; this.id = id; this.salary = salary; } public String toString() { return "name=" + name + "; id=" + id + "; salary=" + salary; } } public class DeserializationTest { public static void main(String args[]) { //Deserialization of object try { FileInputStream fis = new FileInputStream("serial.txt"); ObjectInputStream ois = new ObjectInputStream(fis); Employee obj = (Employee)ois.readObject(); ois.close(); System.out.println("Employee Object: " + obj); } catch(Exception ex) { System.out.println("Error: " + ex.toString()); } } }Output:
$ javac DeserializationTest.java $ java DeserializationTest Employee Object: name=Employee1; id=1002; salary=5600.5
Java Tutorial
Privacy Policy | Copyright2020 - All Rights Reserved. | Contact us | Report website issues in Github | Facebook page | Google+ page