Java / Java File I/O and Serialization

Object Serialization and Deserialization

In this tutorial, you'll explore the process of object serialization and deserialization in Java. These concepts are important for storing and retrieving the state of objects.

Tutorial 4 of 5 5 resources in this section

Section overview

5 resources

Explores reading, writing, and manipulating files in Java.

1. Introduction

1.1 Tutorial's Goal

The goal of this tutorial is to introduce you to the concepts of object serialization and deserialization in Java.

1.2 What Will You Learn?

By the end of this tutorial, you will be able to understand the concepts of object serialization and deserialization in Java, write code to serialize and deserialize objects, and understand the use cases and best practices.

1.3 Prerequisites

Before starting this tutorial, you should have a basic understanding of Java, including knowledge of Java classes and objects.

2. Step-by-Step Guide

2.1 Concepts

Serialization is the process of converting an object's state to a byte stream, and it's primarily used in networking programming and RMI (Remote Method Invocation), while deserialization is the reverse process of creating an object from a byte stream.

2.2 Examples

Serialization

To serialize an object, we will use ObjectOutputStream.

FileOutputStream fileOutputStream = new FileOutputStream("ser.txt");
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(object);
objectOutputStream.close();

Deserialization

To deserialize an object, we will use ObjectInputStream.

FileInputStream fileInputStream = new FileInputStream("ser.txt");
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
MyClass object = (MyClass) objectInputStream.readObject();
objectInputStream.close();

2.3 Best Practices and Tips

  1. Always close the stream after use to avoid memory leaks.
  2. The class whose objects are to be serialized should implement Serializable interface.

3. Code Examples

3.1 Serialization

import java.io.*;

class Employee implements Serializable {
    String name;
    int age;

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

public class SerializeExample {
    public static void main(String[] args) {
        Employee e = new Employee("John Doe", 30);
        try {
            FileOutputStream fileOut = new FileOutputStream("employee.ser");
            ObjectOutputStream out = new ObjectOutputStream(fileOut);
            out.writeObject(e);
            out.close();
            fileOut.close();
        } catch (IOException i) {
            i.printStackTrace();
        }
    }
}

In the above code, we create an Employee class that implements Serializable interface. In the main method, we create an object of Employee, serialize it, and save it in "employee.ser".

3.2 Deserialization

import java.io.*;

public class DeserializeExample {
    public static void main(String[] args) {
        Employee e = null;
        try {
            FileInputStream fileIn = new FileInputStream("employee.ser");
            ObjectInputStream in = new ObjectInputStream(fileIn);
            e = (Employee) in.readObject();
            in.close();
            fileIn.close();
        } catch (IOException i) {
            i.printStackTrace();
            return;
        } catch (ClassNotFoundException c) {
            System.out.println("Employee class not found");
            c.printStackTrace();
            return;
        }
        System.out.println("Deserialized Employee...");
        System.out.println("Name: " + e.name);
        System.out.println("Age: " + e.age);
    }
}

In the above code, we deserialize the "employee.ser" file and read the Employee object from it.

4. Summary

In this tutorial, you learned about object serialization and deserialization in Java, wrote code to serialize and deserialize objects, and understood its use cases and best practices.

5. Practice Exercises

5.1 Exercise 1

Create a Student class with name, age, and grade attributes and serialize an object of this class.

5.2 Solution

import java.io.*;

class Student implements Serializable {
    String name;
    int age;
    int grade;

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

public class SerializeStudent {
    public static void main(String[] args) {
        Student s = new Student("John Doe", 16, 10);
        try {
            FileOutputStream fileOut = new FileOutputStream("student.ser");
            ObjectOutputStream out = new ObjectOutputStream(fileOut);
            out.writeObject(s);
            out.close();
            fileOut.close();
        } catch (IOException i) {
            i.printStackTrace();
        }
    }
}

5.3 Exercise 2

Deserialize the "student.ser" file created in the previous exercise and read the Student object from it.

5.4 Solution

import java.io.*;

public class DeserializeStudent {
    public static void main(String[] args) {
        Student s = null;
        try {
            FileInputStream fileIn = new FileInputStream("student.ser");
            ObjectInputStream in = new ObjectInputStream(fileIn);
            s = (Student) in.readObject();
            in.close();
            fileIn.close();
        } catch (IOException i) {
            i.printStackTrace();
            return;
        } catch (ClassNotFoundException c) {
            System.out.println("Student class not found");
            c.printStackTrace();
            return;
        }
        System.out.println("Deserialized Student...");
        System.out.println("Name: " + s.name);
        System.out.println("Age: " + s.age);
        System.out.println("Grade: " + s.grade);
    }
}

In the code above, we are deserializing the "student.ser" file and reading the Student object from it.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

PDF to Word Converter

Convert PDF files to editable Word documents.

Use tool

Time Zone Converter

Convert time between different time zones.

Use tool

PDF Password Protector

Add or remove passwords from PDF files.

Use tool

Fake User Profile Generator

Generate fake user profiles with names, emails, and more.

Use tool

Markdown to HTML Converter

Convert Markdown to clean HTML.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help