Java Serialization and Deserialization Examples

In Java, Serialization means converting Java objects into a byte stream; Deserialization means converting the serialized object’s byte stream back to the original Java object. Table of contents. 1. Hello World Java Serialization 2. java.io.NotSerializableException 3. What is serialVersionUID? 4. What is transient? 5. Serialize Object to File 6. Why need Serialization in Java? 7. …

Read more

How to read an object from file in Java (ObjectInputStream)

This example shows how to use ObjectInputStream to read a serialized object from a file in Java, aka Deserialization. public static Object readObjectFromFile(File file) throws IOException, ClassNotFoundException { Object result = null; try (FileInputStream fis = new FileInputStream(file); ObjectInputStream ois = new ObjectInputStream(fis)) { result = ois.readObject(); } return result; } // Convert byte[] to …

Read more

How to write an object to file in Java (ObjectOutputStream)

This example shows how to use ObjectOutputStream to write objects to a file in Java, aka Serialization. public static void writeObjectToFile(Person obj, File file) throws IOException { try (FileOutputStream fos = new FileOutputStream(file); ObjectOutputStream oos = new ObjectOutputStream(fos)) { oos.writeObject(obj); oos.flush(); } } Note More Java Serialization and Deserialization examples 1. Java object We can …

Read more