Java Tutorials
  • Introduction to Java
    • What is Java?
    • History and Features of Java
    • Java Virtual Machine (JVM) and Bytecode
    • Why Java?
  • Setting up Java Development Environment
    • Installing Java Development Kit (JDK)
    • JDK vs JRE
    • Setting up IDE (Eclipse, IntelliJ, NetBeans) or Text Editor (VS Code, Sublime Text)
  • Basic Java
    • First Java Program : Hello World
    • Variable
    • Data Type
    • Constant
    • Date and Format
    • Operator
    • Condition
    • Looping
    • Function
    • Variadic Function
    • Enums
    • Array
    • Collection
    • Exception and Exception Handling
    • Naming Convention
  • Object Oriented Programming (OOP)
    • Classes and Objects
    • Inheritance and Polymorphism
    • Encapsulation and Abstraction
  • File Handling
    • Reading and Writing Binary File
    • Reading and Writing Text File
    • Serialization and Deserialization
  • Multithreading
    • Creating and Running Threads
    • Synchronization
    • Thread Pools and Executors
  • Collections API
    • Sorting and Comparable
    • Searching and Comparator
  • Java Database Connectivity (JDBC)
    • Introduction and Life Cycle
    • Connection to Database (MySQL)
    • Downloading JDBC Drivers for Various Databases
    • Maven and Gradle JDBC Drivers for Various Databases
    • JDBC URL Formats
    • Statement and PreparedStatement
    • CallableStatement
    • Selecting Data using JDBC
    • Inserting Data using JDBC
    • Updating Data using JDBC
    • Deleting Data using JDBC
    • Invoking Function and Stored Procedure using JDBC
  • Lambda
    • Introduction to Lambda Expressions
    • Functional Interface
    • Filtering, Mapping, Reducing
    • Lambda Expressions in Collections
    • Method References
    • Functional Programming Concepts
    • Stream API
    • Error Handling in Lambda Expressions
    • Optional in Functional Programming
    • Parallel Processing with Lambda
    • Functional Programming Patterns
    • Advanced Topics in Lambda Expressions
    • Best Practices and Design Patterns
    • Real-World Use Cases and Examples
Powered by GitBook
On this page
  1. File Handling

Serialization and Deserialization

File handling in Java allows you to perform various operations on files, including serialization and deserialization. Serialization is the process of converting objects into a byte stream, while deserialization is the process of reconstructing objects from a byte stream. This can be particularly useful when you want to store Java objects persistently or send them across a network.

1. Serialization:

Serialization Example:

import java.io.*;

class Student implements Serializable {
    private String name;
    private int rollNumber;

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

    public void display() {
        System.out.println("Name: " + name);
        System.out.println("Roll Number: " + rollNumber);
    }
}

public class SerializationExample {
    public static void main(String[] args) {
        Student student = new Student("Alice", 123);

        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("student.ser"))) {
            oos.writeObject(student);
            System.out.println("Object serialized successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In this example, a Student object is serialized and saved into a file named "student.ser". The ObjectOutputStream class is used to write the object to the file. The Student class implements Serializable.

2. Deserialization:

Deserialization Example:

import java.io.*;

class Student implements Serializable {
    private String name;
    private int rollNumber;

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

    public void display() {
        System.out.println("Name: " + name);
        System.out.println("Roll Number: " + rollNumber);
    }
}

public class DeserializationExample {
    public static void main(String[] args) {
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("student.ser"))) {
            Student student = (Student) ois.readObject();
            student.display();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

In this example, the Student object is deserialized from the "student.ser" file using the ObjectInputStream class. The object is cast back to the Student class, and its display() method is called.

Explanation:

  • Serialization:

    • ObjectOutputStream is used to serialize objects. It writes primitive data types and graphs of Java objects to an OutputStream.

    • The class to be serialized (Student in this case) implements the Serializable interface, which is a marker interface indicating the class is serializable.

    • Serialized objects can be saved to a file for future use or transmitted over a network.

  • Deserialization:

    • ObjectInputStream is used for deserialization. It reads objects from an InputStream and deserializes them.

    • The class being deserialized must have the same serialVersionUID as the class that was serialized.

    • The deserialized object can be cast back to its original class for further use.

Remember to handle IOException and ClassNotFoundException to ensure your file handling, serialization, and deserialization operations are error-free and robust.

PreviousReading and Writing Text FileNextCreating and Running Threads

Last updated 1 year ago