Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Serializing and De-serializing Objects in Java

In this tutorial, we take a look at how one can implement serialization and deserialization techniques when programming in Java. First, we shall explain what the process basically is and how it can be advantageous.

If you have been into Java programming, you must well aware of the term serialization. Serialization in Java brings forward several advantages, something that we shall discuss. Before that, we shall learn what serialization actually is.

What is serialization?

Serialization can basically be described as the process of turning an object that exists, into a byte array, i.e. a sequence of bytes. Such a byte array is the representation of the class of the object, meaning that it represents the objects’ data, and information about its type and data types that are stored in it.

Once a serialized object is written into a file, it can be obtained and read from the file, which is naturally the deserialization process. The information and bytes that represent the object, along with its data, can be utilized from recreating the object in the memory.

Figure 1.Serialization and de-serialization process

Why would you implement serialization and deserialization?

Implementing sterilization in Java helps us for several reasons. We shall discuss a few of them.

  • Communication – this occupies the first place in the list. Say there are two machines that are running the same program and there is the need for communication, building of an object consisting of information to be transmitted can easily be done by one machine. The object can then be serialized to the other machine.
  • Storage – Storing the state of a particular operation to a database can be easily implemented after serialization of it into a byte array. This can then be used for retrieval later when necessary.
  • Exact copy – if you wish to have an exact copy of any particular object, but at the same time, do not wish to code your very own clone class, serialization can be helpful. Here too, you can first serialize the object into a byte array. Later, you can de-serialize it into another object and get the job done.
  • Caching – This is pretty similar to the copying style, but often you might notice that an object takes quite a lump sum time to build, while it would take a lot less time to de-serialize. So, in such cases, caching the object to a file and then later reading it can be a better procedure than having to hold a very large object in the memory.
  • Cross synchronization for JVM – Across various JVMs running on different architectures, serialization works pretty easy.

Classes for Object Streams

There are basically two classes for Object Streams that are used for serialization and de-serialization. These are –

  • ObjectInputStream
  • ObjectOutputStream.

ObjectInputStream

  • This is a Java class that is used for the deserialization process of object that have been serialized and also primitive data.
  • It is responsible for reading the object from the object graph stored by using FileInputStream.
  • The readObject() method is the main object used for deserialization of the object. It reads the object class, the class signature, and also the class’ non-transient and non-static fields, along with super types.

ObjectOutputStream

  • This is a Java class that is used for storing primitives and also the graph of Java objects. This is made available for reading data, to the ObjectInputStream.
  • This class does not save super class or sub class data. However, it can be done by making use of the method writeObject() or using primitive data type functions with DataOutput support.
  • The main method in this Java class is the writeObject() method. It purpose is to serialize objects directly.

The purpose of the Transient keyword

There may often be cases where we wish to store just specific parts of the object, which means leaving out certain fields like from stored objects. This generally concerns sensitive information, such as the likes of passwords.

In such scenarios, we make use of the transient keyword to mark those fields that we wish to shield from being saved during the process of serialization.

An example can be – transient private String passwrd

Now, we shall see how a demonstration for serialization works, followed by the de-serialization process.

Say we have a Workers class that implements an interface Serializable.

Listing 1: Workers class

public class Workers implements java.io.Serializable
{
   public String name;
   public String resaddress;
   public transient int ID;
   public int numbr;   
   public void checkmail()
   {
      System.out.println("Mailing for a check to " + name + " " + resaddress);
   }
}

Now, some things to note for successful serialization of a class are –

  • Implementation of the java.io.Serializable by the class.
  • All fields must be serializable, barring the ones that have been marked with transient.

Serialization of an Object

We make use of the ObjectOutputStream class for the serialization process of the object. The program Serialdemo given below is responsible for instantiating a Workers object and then serializing it to a file.

Listing 2: Sample serialize demo

import java.io.*;
public class Serialdemo
{
   public static void main(String [] args)
   {
      Workers work = new Workers();
      work.name = "Donald Ray";
      work. resaddress= "Broad Street, New England City";
      work.ID = 132563933;
      work.numbr = 222;      
      try
      {
         FileOutputStream fileoutput =
         new FileOutputStream("/tmp/workers.ser");
         ObjectOutputStream output = new ObjectOutputStream(fileoutput);
         output.writeObject(work);
         output.close();
         fileoutput.close();
         System.out.printf("Serialized data has been saved in /tmp/workers.ser");
      }catch(IOException iexp)
      {
          iexp.printStackTrace();
      }
   }
}

Once the program finishes execution, a file by the name of workers.se is created. As such, the above program does not generate an output.

Also note that the standard convention for file naming after the serialization of an object to a file is to add a .ser extension.

De-serialization of an Object

The Deserialdemo program code given below is used to for the deserialization of the Workers object created in the Serialdemo program.

Listing 3: Sample De-serialize demo

import java.io.*;
public class Deserialdemo
{
   public static void main(String [] args)
   {
      Workers work = null;  
try
      {
         FileInputStream fileinput = new FileInputStream("/tmp/workers.ser");
         ObjectInputStream input = new ObjectInputStream(fileinput);
         work = (Workers) input.readObject();
         input.close();
         fileinput.close();
      }catch(IOException iexp)
      {
         iexp.printStackTrace();
         return;
      }catch(ClassNotFoundException cnfe)
      {
         System.out.println("Workers class could not be found!!");
         cnfe.printStackTrace();
         return;
      }
      System.out.println("De-serialized Workers...");
      System.out.println("Name: " + work.name);
      System.out.println("Residential Address: " + work.resaddress);
      System.out.println("ID: " + work.ID);
      System.out.println("Number: " + work.numbr);
    }
}

The result of the above program code would be –

Deserialized Workers...
Name: Donald Ray
Residential Address: Broad Street, New England City 
ID: 0
Number: 222

Now, there are certainly a few points that need to be taken care of here.

  • The try/catch block has been written to catch a ClassNotFoundException that is declared by the method readObject(). When the JVM is asked to de-serialize an object, it should be able to find the class’ bytecode. However, if this cannot be found during the process, then the ClassNotFoundException is thrown.
  • The return value of the readObject is cast to a Workers reference.
  • During the serialization process, the value of the ID field was 132563933. However, due to the field being marked as transient, we see that the value was not sent to the output stream. As a result, the ID value of the Workers object has been shown as 0.

We shall also take a look into another example that implements both serialization and de-serialization.

Listing 4: Users.java

 
import java.io.Serializable;
 
public class Users implements Serializable {
 
    /**
     * Generation of serial version ID
     */
    private static final long serialversionID = -5585768630525647L;
 
    private String name;
    private String user_name;
    transient private String pass_word;
 
    @Override
    public String tostring() {
        // TODO Auto-generated method 
        String value = "Name: " + name + "\n User Name: " + user_name
                + "\n Password: " + pass_word;
        return value;
    }
 
    /**
     * Methods Setters & getters
     */
 
    public String getname() {
        return name;
    }
 
    public void setname(String name) {
        this.name = name;
    }
 
    public String getusername() {
        return user_name;
    }
 
    public void setusername(String username) {
        this.user_name = user_name;
    }
 
    public String getpassword() {
        return pass_word;
    }
 
    public void setpassword(String password) {
        this.pass_word = pass_word;
    }
}
 

Listing 5: Serialutil.java

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
 
/**
 * This class basically is a utility class for performing serialization and
 * de-serialization processes when provided the required information.
 *
 */
public class Serialutil {
 
    /**
     * To de-serialize to object from a given file, we use the general object 
     * so that it works for all Java classes. */
    public static Object deserialize(String filename) throws IOException,
            ClassNotFoundException {
        FileInputStream finputs = new FileInputStream(filename);
        BufferedInputStream binputs = new BufferedInputStream(finputs);
        ObjectInputStream oinputs = new ObjectInputStream(binputs);
        Object objt = oinputs.readObject();
        oinputs.close();
        return objt;
    }
 
    /**
     * Serializing the given object and saving it to a given file
     */
    public static void serialize(Object objt, String filename)
            throws IOException {
        FileOutputStream foutputs = new FileOutputStream(filename);
        BufferedOutputStream boutputs = new BufferedOutputStream(foutputs);
        ObjectOutputStream ooutputs = new ObjectOutputStream(boutputs);
        ooutputs.writeObject(objt);
        ooutputs.close();
    }
}
                                                                                  

In the above code, we have made use of –

  • File Streams to undertake file related operations that are wrapped in.
  • Buffered Streams for speeding of operations that are later wrapped into.
  • Object Streams for serializing and de-serializing.

Listing 6: Serialtest.java

 
import java.io.IOException;
 
public class Serialtest {
 
    public static void main(String[] args) {
        Users users = new Users();
        users.setname("John");
        users.setusername("Johny12");
        users.setpassword("$");
 
        try {
            /**
             *  Serialization the object
             */
            Serialutil.serialize(user, "serialize.txt");
 
            /**
             * De-serialization of the object
             */
            Users newuser = (Users) 
Serialutil.deserialize("serialize.txt");
            System.out.println(newuser.tostring());
 
        } 
 
catch (IOException | ClassNotFoundException excp) 
  {
            excp.printStackTrace();
        }
    }
}
 

Output of the above program –

Name: John
User Name: Johny12
Password: null

The value of the password is shown as null because it has been declared as a transient field, and during the serialization process, a default value was assigned to it.

Conclusion

In the above tutorial, we have first explained what serialization and de-serialization in Java is all about. Then we moved onto explaining why they are implemented and how useful they can be. We also took on some important concepts (like classes for object streams and the use of transient) that concern the processes and explained their uses.

Finally, we demonstrated, through two very simply laid out examples, how the process of both, serialization and de-serialization works. The output given at the end of very program also helped in verifying our programs. We hope that this tutorial can aid in your quest to learn the basics concerning serialization and de-serialization in Java programming.



Website: www.techalpine.com Have 16 years of experience as a technical architect and software consultant in enterprise application and product development. Have interest in new technology and innovation area along with technical...

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login