Page 1 of 1

Object Serialization An introduction into object serialization Rate Topic: -----

#1 m-e-g-a-z  Icon User is offline

  • Winning
  • member icon


Reputation: 496
  • View blog
  • Posts: 1,453
  • Joined: 19-October 09

Posted 25 February 2010 - 08:51 AM

*
POPULAR

This tutorial will be about Object Serialization.

Introduction

What is object serialization?


In simple terms, object serialization is a way of providing a program to read or write an object. It allows Java objects and primitives to be encoded into a byte stream (a file) suitable for streaming. Examples of this could be within a network or even a file-system.

Why do we use object serialization?


The Java platform allows us to create reusable objects in memory. However, all of those objects exist only as long as the Java virtual machine remains running. It would be nice if the objects we create could exist beyond the lifetime of the virtual machine, wouldn't it? Well, with object serialization, you can flatten your objects and reuse them in powerful ways.

With object serialization, an object's state is saved into a file as a sequence of bytes. Once an object is saved into a file you would need to retrieve it when needed right? This is a simple reverse process of converting those bytes into a live object.

An example using object serialization


Lets say we have a class called Mixture, it includes an arraylist of integers and strings.

import java.util.*;

public class Mixture 
{
	
	public static void main (String [] args) 
	{
		//Create new arraylist
		ArrayList m = new ArrayList();
                //add to arraylist
		m.add(1);
		m.add("hello");
		m.add(4);
                //print arraylist m
		System.out.println(m);

			
	}
	  	
}



Right, now we have this great class called Mixture that contains important word(s) and number(s) in an arraylist, but imagine if we wanted to store this in a database?

This is were object serialization comes into place :) .

For us to save a Mixture object in a file, we will need to use the Serializable Class or simpler the IO Class.

import java.io.*;
import java.util.*;

public class Mixture2 
{
          //Main method throws Exception  
        public static void main (String []args) throws IOException
        { 
        	  //Delcare arraylist called m
                ArrayList  m = new ArrayList();
               //Add to arraylist m
                m.add(1);
                m.add("hello");
                m.add(4);
                System.out.println(m);
                
               /*Create a object from the ObjectOutputStream class and delcare
                it out and instantiate a FileOutputStream and call our new file mapFile*/
                ObjectOutputStream out = new ObjectOutputStream (new FileOutputStream("mapFile"));
               //writeObject method stores the state of the object               
                out.writeObject(m);
                //flush the stream
                out.flush();
                //close the stream
                out.close();

        
                
        }
          
        
}



Apart from importing a new class and throwing an exception, you can notice that just a slight amount of code has been added to the Mixture2 class.

Once compiling Mixture2, there should be a file created within the same directory as Mixture2. This file should be called by default mapFile or what you changed it too.

This file will then give us a strange looking amount of binary codes. This is just a binary representation of the object we saved.

This data could then be stored into a database or a server but what would be do if we wanted to retrieve the object and use it as part of our code?

This example below shows you exactly how to do that.

import java.io.*;
import java.util.*;

public class Mixture3 {

	public static void main(String[] args) throws IOException {

		// Creates a new ArrayList called map
		ArrayList map = new ArrayList ();
		try{	
			/* Creates a new Object of the FileInputStream class 
	        which file name as parameters.  This is to define the
	        file we are reading from */
			FileInputStream fis = new FileInputStream("mapFile");
			/* Create a new Object of the ObjectInputStream class
            which has the variable as the parameters to the object we
            created above */
			ObjectInputStream ois = new ObjectInputStream(fis);
			/* We would then need to type cast and read file using
	        readObject Method */
			map =  (ArrayList) ois.readObject();
			//Close ObjectInputStream
			ois.close();
			//Using a simple enhanced for loop to print contents of map
			for (Object s:map) 
				//Print out elements
				System.out.println(s);

		}
		//Catch Exception
		catch (Exception e)
		{
			//Prints out an error statement
			System.out.println("File Not Found");
		}   

	}
}



This then gives us an output of

1
hello
4



which is the elements we previously stored in the Mixture class.

Last but not least, remember only use Object Serialization when it is needed.

Part 2 of this tutorial will be out soon which introduces you to Object Serialization within a client-server environment and a database.

I hope you have enjoyed reading this tutorial :).

m-e-g-a-z

Is This A Good Question/Topic? 8
  • +

Replies To: Object Serialization

#2 nick2price  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 561
  • View blog
  • Posts: 2,826
  • Joined: 23-November 07

Posted 11 July 2010 - 07:32 AM

Nice tutorial. Funny enough, I have never even looked at serialization before. One question though. Why would this be chosen over just saving contents straight to a file using filewriter? Is it a memory thing or something?

If this could be used on say class objects, say a Student object, I can understand how powerful it could be.

This post has been edited by nick2price: 11 July 2010 - 07:35 AM

Was This Post Helpful? 0
  • +
  • -

#3 m-e-g-a-z  Icon User is offline

  • Winning
  • member icon


Reputation: 496
  • View blog
  • Posts: 1,453
  • Joined: 19-October 09

Posted 11 July 2010 - 08:27 AM

I think it's simply an ideal way in terms of Storing an object in a file and easily retrieving it whenever you want. If a class implements the Serializable interface, that class object can be serialized thus allowing it to be stored on a network which would be much more ideal than writing the whole classes variable contents to a file. Writing to a file is more time efficient but it really depends on what you need it for.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1