Serialization program with 3 files import java.io.*; public class Student implements Serializable { private int id; private String name; private double percentage; // use transient and static variables to check if they are saved public Student(int id, String name, double percentage) { this.id = id; this.name = name; this.percentage = percentage; } public String toString() { return "ID: "+this.id+", Name: "+this.name+", Percentage: "+this.percentage; } } import java.io.*; public class SerializationDemo { public static void main(String[] args) { try(FileOutputStream fos = new FileOutputStream("serial.txt"); ObjectOutputStream out = new ObjectOutputStream(fos); ) { System.out.println("Creating a student"); Student s = new Student(100, "John", 98.56); System.out.println(s); out.writeObject(s); System.out.println("Object serialized"); } catch(FileNotFoundException fe){ fe.printStackTrace();} catch(IOException ie){ ie.printStackTrace(); } } } import java.io.*; public class DeserializationDemo { public static void main(String[] args) { try(FileInputStream fis = new FileInputStream("serial.txt"); ObjectInputStream in = new ObjectInputStream(fis); ) { System.out.println("Restoring the object"); Student s = (Student)in.readObject(); System.out.println(s); System.out.println("Deserialization Done"); } catch(ClassNotFoundException ce){ ce.printStackTrace();} catch(IOException ie){ ie.printStackTrace(); } } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter