Java serialization
In Java, serialization is the process of converting an object into a stream of bytes so that it can be stored on disk or transmitted over a network. Deserialization is the reverse process of converting a stream of bytes back into an object.
Java provides a built-in mechanism for serialization and deserialization through the java.io.Serializable
interface. To enable serialization for an object, you need to implement the Serializable
interface. Here's an example:
import java.io.*; public class Person implements Serializable { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } }
In this example, we've defined a Person
class that implements the Serializable
interface. This means that instances of the Person
class can be serialized and deserialized using Java's built-in serialization mechanism.
To serialize an object, you can use a ObjectOutputStream
and write the object to a file or a stream:
Person person = new Person("John Doe", 30); try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("person.ser"))) { oos.writeObject(person); } catch (IOException e) { e.printStackTrace(); }
In this example, we create a Person
object and serialize it to a file called person.ser
using an ObjectOutputStream
.
To deserialize an object, you can use a ObjectInputStream
to read the object from a file or a stream:
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("person.ser"))) { Person person = (Person) ois.readObject(); System.out.println("Name: " + person.getName()); System.out.println("Age: " + person.getAge()); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); }
In this example, we deserialize the Person
object from the person.ser
file using an ObjectInputStream
and print out its name and age.