Java Serializable implement with custom serialization method
import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.Serializable; class Main {/*www. ja v a 2 s . c o m*/ public static void main(String[] args) { Language object1 = new Language(1, "HTML"); Language object2 = new Language(2, "CSS"); try { OutputStream fout = new FileOutputStream("ser.txt"); ObjectOutput oout = new ObjectOutputStream(fout); oout.writeObject(object1); oout.writeObject(object2); fout.close(); oout.close(); InputStream inputStream = new FileInputStream("ser.txt"); ObjectInput objectInput = new ObjectInputStream(inputStream); System.out.println((Language) objectInput.readObject()); System.out.println((Language) objectInput.readObject()); objectInput.close(); inputStream.close(); } catch (Exception ioe) { ioe.printStackTrace(); } } } class Language implements Serializable { private static final long serialVersionUID = 1L; private Integer id; private String name; public Language(Integer id, String name) { this.id = id; this.name = name; } @Override public String toString() { return "Language [id=" + id + ", name=" + name + "]"; } private void writeObject(ObjectOutputStream oos) { try { System.out.println("Internally Write Method Called"); oos.writeInt(this.id); oos.writeObject(this.name); } catch (IOException e) { e.printStackTrace(); } } private void readObject(ObjectInputStream ois) { try { System.out.println("Internally Read Method Called"); id = ois.readInt(); name = (String) ois.readObject(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }