How do I decompress Java objects?

In the previous example How do I compress Java objects? we have manage to compress Java objects and stored them in file. In this example we will read the file and reconstruct the compressed objects. For the User class you can see in the previous example mentioned above.

package org.kodejava.util.zip;

import org.kodejava.util.support.User;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.zip.GZIPInputStream;

public class UnzipObjectDemo {
    public static void main(String[] args) {
        File file = new File("user.dat");
        try (FileInputStream fis = new FileInputStream(file);
             GZIPInputStream gis = new GZIPInputStream(fis);
             ObjectInputStream ois = new ObjectInputStream(gis)) {

            User admin = (User) ois.readObject();
            User foo = (User) ois.readObject();

            System.out.println("Admin = [" + admin + "]");
            System.out.println("Foo = [" + foo + "]");
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

Running the code snippet above will give us the following output:

Admin = [User{id=1, username='admin', password='secret', firstName='System', lastName='Administrator'}]
Foo = [User{id=2, username='foo', password='secret', firstName='Foo', lastName='Bar'}]

How do I create a client-server socket communication?

In this example you’ll see how to create a client-server socket communication. The example below consist of two main classes, the ServerSocketExample and the ClientSocketExample. The server application listen to port 7777 at the localhost. When we send a message from the client application the server receive the message and send a reply to the client application.

The communication in this example using the TCP socket, it means that there is a fixed connection line between the client application and the server application.

package org.kodejava.net;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.ClassNotFoundException;
import java.lang.Runnable;
import java.lang.Thread;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerSocketExample {
    private static final int PORT = 7777;
    private ServerSocket server;

    private ServerSocketExample() {
        try {
            server = new ServerSocket(PORT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        ServerSocketExample example = new ServerSocketExample();
        example.handleConnection();
    }

    private void handleConnection() {
        System.out.println("Waiting for client message...");

        // The server do a loop here to accept all connection initiated by the
        // client application.
        while (true) {
            try {
                Socket socket = server.accept();
                new ConnectionHandler(socket);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

class ConnectionHandler implements Runnable {
    private final Socket socket;

    ConnectionHandler(Socket socket) {
        this.socket = socket;

        Thread t = new Thread(this);
        t.start();
    }

    public void run() {
        try {
            // Read a message sent by client application
            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
            String message = (String) ois.readObject();
            System.out.println("Message Received: " + message);

            // Send a response information to the client application
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
            oos.writeObject("Hi...");

            ois.close();
            oos.close();
            socket.close();

            System.out.println("Waiting for client message...");
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
package org.kodejava.net;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.ClassNotFoundException;
import java.net.InetAddress;
import java.net.Socket;

public class ClientSocketExample {
    public static void main(String[] args) {
        try {
            // Create a connection to the server socket on the server application
            InetAddress host = InetAddress.getLocalHost();
            Socket socket = new Socket(host.getHostName(), 7777);

            // Send a message to the client application
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
            oos.writeObject("Hello There...");

            // Read and display the response message sent by server application
            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
            String message = (String) ois.readObject();
            System.out.println("Message: " + message);

            ois.close();
            oos.close();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

To test the application you need to start the server application. Each time you run the client application it will send a message “Hello There…” and in turns the server reply with a message “Hi…”.

How do I store objects in file?

This example demonstrates how to use the java.io.ObjectOutputStream and java.io.ObjectInputStream classes to write and read a serialized object. We will create a Book that implements java.io.Serializable interface. The Book class has a constructor that accept all the book detail information.

To write an object to a stream we call the writeObject() method of the ObjectOutputStream class and pass the serialized object to it. To read the object back we call the readObject() method of the ObjectInputStream class.

package org.kodejava.io;

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

public class ObjectStoreExample {

    public static void main(String[] args) {
        // Create instances of FileOutputStream and ObjectOutputStream.
        try (FileOutputStream fos = new FileOutputStream("books.dat");
             ObjectOutputStream oos = new ObjectOutputStream(fos)) {

            // Create a Book instance. This book object then will be stored in
            // the file.
            Book book = new Book("0-07-222565-3", "Hacking Exposed J2EE & Java",
                    "Art Taylor, Brian Buege, Randy Layman");

            // By using writeObject() method of the ObjectOutputStream we can
            // make the book object persistent on the books.dat file.
            oos.writeObject(book);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // We have the book saved. Now it is time to read it back and display
        // its detail information.
        try (FileInputStream fis = new FileInputStream("books.dat");
             ObjectInputStream ois = new ObjectInputStream(fis)) {

            // To read the Book object use the ObjectInputStream.readObject() method.
            // This method return Object type data, so we need to cast it back the
            // origin class, the Book class.
            Book book = (Book) ois.readObject();
            System.out.println(book.toString());

        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

// The book object will be saved using ObjectOutputStream class and to be read
// back using ObjectInputStream class. To enable an object to be written to a
// stream we need to make the class implements the Serializable interface.
class Book implements Serializable {
    private final String isbn;
    private final String title;
    private final String author;

    public Book(String isbn, String title, String author) {
        this.isbn = isbn;
        this.title = title;
        this.author = author;
    }

    @Override
    public String toString() {
        return "Book{" +
                "isbn='" + isbn + '\'' +
                ", title='" + title + '\'' +
                ", author='" + author + '\'' +
                '}';
    }
}

The result of the code snippet above is:

Book{isbn='0-07-222565-3', title='Hacking Exposed J2EE & Java', author='Art Taylor, Brian Buege, Randy Layman'}