Serialization in Java

Serialization in Java

Object Serialization and Deserialization

Serialization in Java is the process of converting an object into a byte stream, which can then be easily stored in a file or transmitted over a network. Deserialization is the reverse process, where the byte stream is converted back into a copy of the original object. This is particularly useful for sending objects over sockets in networked applications.

Object Serialization

To serialize an object, the class must implement the Serializable interface. This is a marker interface, which means it does not contain any methods but signals to the Java Virtual Machine (JVM) that the object can be serialized.

Here's an example:

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class Person implements Serializable {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public static void main(String[] args) {
        Person person = new Person("John Doe", 30);

        try (FileOutputStream fileOut = new FileOutputStream("person.ser");
             ObjectOutputStream out = new ObjectOutputStream(fileOut)) {
            out.writeObject(person);
            System.out.println("Serialized data is saved in person.ser");
        } catch (IOException i) {
            i.printStackTrace();
        }
    }
}

    

Object Deserialization

To deserialize the object, read the byte stream from a file and convert it back into an object.

Here's an example:

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

public class DeserializePerson {
    public static void main(String[] args) {
        Person person = null;

        try (FileInputStream fileIn = new FileInputStream("person.ser");
             ObjectInputStream in = new ObjectInputStream(fileIn)) {
            person = (Person) in.readObject();
            System.out.println("Deserialized Person...");
            System.out.println("Name: " + person.name);
            System.out.println("Age: " + person.age);
        } catch (IOException i) {
            i.printStackTrace();
        } catch (ClassNotFoundException c) {
            System.out.println("Person class not found");
            c.printStackTrace();
        }
    }
}

    

Sending Objects Over Sockets

Serialization is particularly useful when sending objects over sockets. You can serialize an object on the client-side, send it over a network, and deserialize it on the server-side.

Client-Side Code

import java.io.ObjectOutputStream;
import java.net.Socket;

public class Client {
    public static void main(String[] args) {
        String hostname = "localhost";
        int port = 8080;

        try (Socket socket = new Socket(hostname, port);
             ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream())) {
            Person person = new Person("Jane Doe", 25);
            out.writeObject(person);
            System.out.println("Object sent to the server");
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

    

Server-Side Code

import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public static void main(String[] args) {
        int port = 8080;

        try (ServerSocket serverSocket = new ServerSocket(port)) {
            System.out.println("Server is listening on port " + port);

            while (true) {
                Socket socket = serverSocket.accept();
                System.out.println("New client connected");

                ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
                Person person = (Person) in.readObject();
                System.out.println("Received object:");
                System.out.println("Name: " + person.name);
                System.out.println("Age: " + person.age);
            }
        } catch (IOException | ClassNotFoundException ex) {
            ex.printStackTrace();
        }
    }
}

    

Conclusion 🔚

Serialization and deserialization in Java are powerful mechanisms for converting objects to and from byte streams, making it easy to store objects or transmit them over a network. This is particularly useful in networked applications, where objects need to be sent over sockets.

With these techniques, you can efficiently manage object data in your Java applications. For more advanced topics, explore further into custom serialization, transient fields, and handling versioning in serialized objects.

Want to dive deeper into Java networking? Check out our previous posts:

Stay tuned for more insights and practical examples to enhance your Java programming skills! 💻🌐