Serialization


The ObjectInputStream class is used for deserializing objects from input stream. The serialized data can be store on local drive and then later read by ObjectInputStream to deserialized it back to object instance. Serialization is often use as a way for saving application preferences and game state.

Classes must implement Serializable or Externalizable interfaces for ObjectOutputStream and ObjectInputStream to serialize and deserialize an instance of classes. ObjectInputStream can deserialize primitive types, classes and user defined classes. Following example show how to make object serializable by implementing Serializable interface.

package com.geek.tutorials.io.serializable;

import java.io.Serializable;

public class Class1 implements Serializable{ // Display Comment
This line will make Class1 serializable. You can serialize an instance of this class with ObjectOutputStream and then read it back with ObjectInputStream, which will be explain later in next code section.
	int value;
	
	public Class1(int value){
		this.value = value;
	}
	
	
	public int getValue(){
		return value;
	}
}
					
				

Following code show how you can deserialize serializable class from ObjectInputStream and read it back to instance.

package com.geek.tutorials.io.serializable;

import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.FileOutputStream;
import java.io.FileInputStream;

public class SerializableTest1 {
	
	public static void main(String[] args) {
		Class1 class1 = new Class1(5); // Display Comment
Declare an instance of Class1 that implemented serializable interface and initialized it value field to 5. The value is just for prove the state of the Class1 is being serialized into file.
			
		try{
			// Display Comment
Initialize instance of ObjectOutputStream with FileOutputStream that will output data into serialize1.ser file. Note that you may use any filename you prefer.
			FileOutputStream f = new FileOutputStream("serialize1.ser"); 
			ObjectOutputStream out = new ObjectOutputStream(f);
			
			out.writeObject(class1); //Display Comment
serialize class1 to ObjectOutputStream, then finish the operation with out.close() method.
			out.flush();
			out.close();
						
			FileInputStream f2 = new FileInputStream("serialize1.ser"); 
			ObjectInputStream in = new ObjectInputStream(f2);
			Class1 c1 =(Class1)in.readObject(); //Display Comment
You can use this to deserialize data from the serialized stream.
			in.close();
			
			System.out.println(c1.getValue()); //Display Comment
When you execute this example, you will get value '5' printed on console screen. This is the value pass into the constructor of Class1 before the serialization. It proved that the state of the Class1 instance had been serialized into serialized1.ser file.
			
		}catch(Exception e){
			System.out.println(e);
		}
	}	
}
				
				


Constructor

protected
ObjectInputStream()

Constructs an instance of ObjectInputStream.

Syntax
public ObjectInputStream() throws IOException, SecurityException

Exception
IOException - Error occurs while reading from InputStream.
SecurityException - if security manager denies subclassing.

Example
See Serialization Example

public
ObjectInputStream(InputStream in)

Constructs an instance of ObjectInputStream that read from InputStream.

Syntax
public ObjectInputStream(InputStream out) throws IOException, SecurityException

Parameters
in - IutputStream to read from

Exception
IOException - Error occurs while reading from InputStream.
SecurityException - throw if untrusted subclass try to overrides security-sensitive methods illegally.

Example
See Serialization Example

 


Method

public int
available()

Find out number primitive data(e.g. int, boolean and etc) bytes available to read from this ObjectInputStream.

Syntax
public int available() throws IOException

Exception
IOException - If error occurs during IO operation.

Description
Find out number primitive data(e.g. int, boolean and etc) bytes available to read from this ObjectInputStream. If next byte belongs to serialized object, this method return 0. It is often use together with skipBytes() for skip the primitive data to reach next serialized object in the input stream.

Example
Following example check number of primitive data bytes need to skip before reaching next serialized object in the input stream.

package com.geek.tutorials.io.ObjectInputStream;

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

public class SkipBytesExample {

	public static void main(String args[]){
		try{
			FileOutputStream f = new FileOutputStream("SkipBytesExample.ser");
			ObjectOutput out = new ObjectOutputStream(f);
			
			out.writeInt(10000);
			out.writeInt(200);
			out.writeObject(new Date());
			out.close();		
			
			FileInputStream f2 = new FileInputStream("SkipBytesExample.ser");
			ObjectInputStream in = new ObjectInputStream(f2);
			
	
			int byteCount = in.available(); //Display Comment
call available() to find out the number of primitive data bytes available in the input stream before reaching next serialized object.
			System.out.println(byteCount);
			
			in.skipBytes(byteCount); //Display Comment
call skipBytes() for skip bytes to the next serialized object in the input stream.
			System.out.println(in.readObject());//Display Comment
After skipped primitive data bytes, now it is safe to read serialized object from the input stream.
			
			in.close();
		}catch(Exception e){
			System.out.println(e);
		}
	}
	
}
						
						
public void
close()

Close the underlying input stream.

Syntax
public void close() throws IOException

Exception
IOException - If error occurs while releasing resources.

Description
Call this method when finish deserialization.

Example
See Serialization Example

public void
defaultReadObject()

Read non-static and non-transient fields from the stream.

Syntax
public final void defaultReadObject() throws IOException, ClassNotFoundException, NotActiveException

Exception
IOException - If error occurs while writing or releasing resources.
ClassNotFoundException - If one of the class of the object inside the object that is being deserialized cannot be found.
NotActiveException - If this method is not invoke from readObject() method.

Description
It can only be invoked from readObject() method, and should be the first method that read any data from stream.

protected final
enableResolveObject(boolean enable)

Subclass of ObjectInputStream must invoke this enableResolveObject() method with true parameter in order to successfully overrides resolveObject() method.

Syntax
protected final boolean enableResolveObject(boolean enable) throws SecurityException

Exception
SecurityException - If this input stream was not loaded by default system class loader.

Example
See ObjectOutputStream.annotateClass() for example.

public int
read()

This method read one or more bytes from underlying input stream.

Syntax
public int read() throws IOException
public int read(byte[] buffer, int offset, int count) throws IOException

Exception
ArrayIndexOutOfBoundsException - If count or offset is outside the buffer[] bounds.
IndexOutOfBoundsException - If count < 0.
IOException - If error occurs during IO operations.

public boolean
readBoolean()

Reads a boolean value from object input stream

Syntax
public boolean readBoolean() throws IOException

Exception
IOException - If error occurs while reading data from input stream.

Example
See Serializing and Desrializing Primitive Data Example.

public byte
readByte()

Reads a byte value from object input stream

Syntax
public byte readByte() throws IOException

Exception
IOException - If error occurs while reading data from input stream.

Example
See Serializing and Desrializing Primitive Data Example.

public char
readChar()

Reads a char value from object input stream

Syntax
public char readChar() throws IOException

Exception
IOException - If error occurs while reading data from input stream.

Example
See Serializing and Desrializing Primitive Data Example.

public double
readDouble()

Reads a double value from object input stream

Syntax
public double readDouble() throws IOException

Exception
IOException - If error occurs while reading data from input stream.

Example
See Serializing and Desrializing Primitive Data Example.

public float
readFloat()

Reads a float value from object input stream

Syntax
public float readFloat() throws IOException

Exception
IOException - If error occurs while reading data from input stream.

Example
See Serializing and Desrializing Primitive Data Example.

public void
readFully()

Reads bytes from input stream.

Syntax
public void readFully(byte[] buffer) throws IOException
public void readFully(byte[] buffer, int offset, int count) throws IOException

Exception
IOException - If error occurs while reading data from input stream.
ArrayIndexOutOfBoundsException - If offset or count is outside of buffer[] bounds.
EOFException - If attempt to read from input stream that reached end-of-file.

Description
readFully(byte[] buffer) read buffer.length of bytes from index 0 and place into buffer[]. readFully(byte[] buffer, int offset, int count) read 'count' number of bytes from offset location and place bytes into buffer[].

public int
readInt()

Reads a int value from object input stream

Syntax
public int readInt() throws IOException

Exception
IOException - If error occurs while reading data from input stream.

Example
See Serializing and Desrializing Primitive Data Example.

public long
readLong()

Reads a long value from object input stream

Syntax
public long readLong() throws IOException

Exception
IOException - If error occurs while reading data from input stream.

Example
See Serializing and Desrializing Primitive Data Example.

public final Object
readObject()

Reads an object from object input stream

Syntax
public final Object readObject() throws IOException

Exception
IOException - If error occurs while reading data from underlying input stream.
ClassNotFoundException - If the class of the object's field or the object itself being deserialized cannot be found by class loader.
EOFException - If attempt to read object from input stream that reach end-of-stream.
InvalidClassException - If the class being deserialized cannot not be instantiated.
StreamCorruptedException - If the class descriptor data is inconsistent with target class.

Example
See Serialization Example.

public short
readShort()

Reads a short value from object input stream

Syntax
public long readLong() throws IOException

Exception
IOException - If error occurs while reading data from input stream.

Example
See Serializing and Desrializing Primitive Data Example.

protected void
readStreamHeader()

Reads and check the stream header from the input stream.

Syntax
protected void readStreamHeader() throws IOException, StreamCorruptedException

Exception
IOException - If error occurs while reading data from underlying output stream.

public int
readUnsignedByte()

Reads a unsigned byte value from object input stream

Syntax
public int readUnsignedByte() throws IOException

Exception
IOException - If error occurs while reading data from input stream.

public int
readUnsignedShort()

Reads a unsigned short value from object input stream

Syntax
public int readUnsignedShort() throws IOException

Exception
IOException - If error occurs while reading data from input stream.

public String
readUTF()

Reads a Unicode string from object input stream and return it as a String object instance.

Syntax
public String readUTF() throws IOException

Exception
IOException - If error occurs while reading data from input stream.

Example
See Serializing and Desrializing Primitive Data Example.

protected Class
resolveClass(ObjectStreamClass desc)

Loads the class for later instantiate of object.

Syntax
protected Class resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException

Exception
IOException - If error occurs while locating the class.
ClassNotFoundException - If the class being deserialized not found.

Example
See ObjectOutputStream.annotateClass() for example.

protected Object
resolveObject(Object obj)

Subclass overrides this method to replaces an object from the input stream with another object.

Syntax
protected Object resolveObject(Object obj) throws IOException

Exception
IOException - If error occurs while replacing the object.

Example
See ObjectOutputStream.annotateClass() for example.

public int
skipBytes(int count)

skip number of bytes from the input stream

Syntax
public int skipBytes(int count) throws IOException

Exception
IOException - If error occurs while attempting to skip given number of bytes.
EOFException - If attempting to skip input stream that reached end-of-file.

Example
See available() for example.


Serializing and Desrializing Primitive Data

package com.geek.tutorials.io.ObjectOutputStream;

import java.io.*;

import com.geek.tutorials.io.serializable.Class1;

public class WritePrimitiveExample {

	public static void main(String arg[]){
		try{
			FileOutputStream f = new FileOutputStream("WritePrimiteExample.ser");
			ObjectOutputStream out = new ObjectOutputStream(f);
			
			out.writeBoolean(true); // writes a boolean
			out.writeByte(2); // writes a byte
			out.writeBytes("34"); // writes a bytes
			out.writeChar('D'); // writes a char
			out.writeChars("56"); // writes a chars
			out.writeDouble(6.0); // writes a double
			out.writeFloat(7.0f); // writes a float
			out.writeInt(8); // writes a int
			out.writeLong(999999999); // writes a long
			out.writeShort(10); // writes a short
			out.flush();
			out.close();
						
			FileInputStream f2 = new FileInputStream("WritePrimiteExample.ser");
			ObjectInputStream in = new ObjectInputStream(f2);
			
			boolean boolValue = in.readBoolean(); // read a boolean
			byte byteValue = in.readByte(); // read a byte
			
			int bytesValue = in.readByte(); // read first byte from bytes
			int bytesValue2 = in.readByte(); // read second byte from bytes
			
			char charValue = in.readChar(); // read a char
			
			char chars1 = in.readChar(); // read first char from chars
			char chars2 = in.readChar(); // read second char from chars

			double doubleValue = in.readDouble(); // read a double
			float floatValue = in.readFloat(); // read a float
			int intValue = in.readInt(); // read a int
			long longValue = in.readLong(); // read a long
			short shortValue = in.readShort(); // read a short
			
			in.close();
			
		}catch(Exception e){
			System.out.println(e);
		}
	}
	
	
}