What is Serialization and Deserialization in Java?

What is Serialization and Deserialization in Java?

What is Serialization and Deserialization in Java?

What is Serialization and Deserialization in Java?

Serialization

  • The process of writing state of an object to a file is called Serialization but strictly speaking, it is a process of converting an object from JAVA supported form into either file supported form or network supported form.
  • Serialization in Java allows us to convert an Object to stream that we can send over the network or save it as file or store in DB for later usage.
  • By using FileOutputStream and ObjectOutputStream classes we can achieve serialization.
package com.java4us;

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 Test implements Serializable {
    int i = 10;
    int j = 20;

    Test(int i, int j) {
        this.i = i;
        this.j = j;
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        Test t = new Test(10, 20);
        System.out.println(t.i + "..." + t.j); //10...20
        FileOutputStream fos = new FileOutputStream("file1.txt");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(t);
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

*