Object Serialization And De-Serialization In Java To Filesystem

Object Serialization:
In computer science, in the context of data storage and transmission, serialization is the process of converting an object into a sequence of bits so that it can be persisted on a storage medium (such as a file, or a memory buffer) or transmitted across a network connection link. When the resulting series of bits is reread according to the serialization format, it can be used to create a semantically identical clone of the original object. For many complex objects, such as those that make extensive use of references, this process is not straightforward.

This process of serializing an object is also called deflating or marshalling an object. The opposite operation, extracting a data structure from a series of bytes, is deserialization (which is also called inflating or unmarshalling).

Advantages Of Object Serialization:
Serialization has a number of advantages. It provides:

  • A method of persisting objects which is more convenient than writing their properties to a text file on disk, and re-assembling them by reading this back in.
  • A method of issuing remote procedure calls, e.g., as in SOAP
  • A method for distributing objects, especially in software componentry such as COM, CORBA, etc.
  • A method for detecting changes in time-varying data.

Serialization In Java:
Java provides automatic serialization which requires that the object be marked by implementing the java.io.Serializable interface. Implementing the interface marks the class as “okay to serialize,” and Java then handles serialization internally. There are no serialization methods defined on the Serializable interface, but a serializable class can optionally define methods with certain special names and signatures that if defined, will be called as part of the serialization/deserialization process. The language also allows the developer to override the serialization process more thoroughly by implementing another interface, the Externalizable interface, which includes two special methods that are used to save and restore the object’s state.

There are three primary reasons why objects are not serializable by default and must implement the Serializable interface to access Java’s serialization mechanism.

  • Not all objects capture useful semantics in a serialized state. For example, a Thread object is tied to the state of the current JVM. There is no context in which a deserialized Thread object would maintain useful semantics.
  • The serialized state of an object forms part of its class’s compatibility contract. Maintaining compatibility between versions of serializable classes requires additional effort and consideration. Therefore, making a class serializable needs to be a deliberate design decision and not a default condition.
  • Serialization allows access to non-transient private members of a class that are not otherwise accessible. Classes containing sensitive information (for example, a password) should not be serializable or externalizable.

The standard encoding method uses a simple translation of the fields into a byte stream. Primitives as well as non-transient, non-static referenced objects are encoded into the stream. Each object that is referenced by the serialized object and not marked as transient must also be serialized; and if any object in the complete graph of non-transient object references is not serializable, then serialization will fail. The developer can influence this behavior by marking objects as transient, or by redefining the serialization for an object so that some portion of the reference graph is truncated and not serialized.

It is possible to serialize Java objects through JDBC and store them into a database.

While Swing components do implement the Serializable interface, they are not portable between different versions of the Java Virtual Machine. As such, a Swing component, or any component which inherits it, may be serialized to an array of bytes, but it is not guaranteed that this storage will be readable on another machine. [Source of this text Wikipedia]

The following program demonstrates how any object can be serialized. The first class is a simple object which has to be serialized/deserialized. The second class serializes and saves the object to the file, and then reads the object back from the file.

The Object to Serialize

package com.kushal.serialization;

 * @author Kushal Paudyal
 * www.sanjaal.com/java
 * Last Modified 09/01/2009 mm-dd-yyyy
import java.io.Serializable;

public class MyObjectToSerialize implements Serializable {

	private String firstName;

	private String lastName;

	private int age;

	public MyObjectToSerialize(String firstName, String lastName, int age) {
		this.firstName = firstName;
		this.lastName = lastName;
		this.age = age;

	public String toString() {
		return firstName + " " + lastName + ", " + age;


That Class that does the serialization/deserialization job.

package com.kushal.serialization;
 * @author Kushal Paudyal
 * www.sanjaal.com/java
 * Last Modified 09/01/2009 mm-dd-yyyy
 * A class that saves and loads a serialized object.
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 ObjectSerialization {

	 * Saves an object to the file
	private static void saveObject(Serializable object, String filename)
			throws IOException {
		ObjectOutputStream objstream = new ObjectOutputStream(
				new FileOutputStream(filename));

	 * Loads an object from the file
	private static Object loadObject(String filename)
			throws ClassNotFoundException, IOException {
		ObjectInputStream objstream = new ObjectInputStream(
				new FileInputStream(filename));
		Object object = objstream.readObject();
		return object;

	public static void main(String[] args) {
		MyObjectToSerialize original = new MyObjectToSerialize("Christopher","Walken", 64);
		System.out.println("Original Object:t" + original);
		try {
			saveObject(original, "C:/object.ser");
			MyObjectToSerialize loaded = (MyObjectToSerialize) loadObject("C:/object.ser");
			System.out.println("Loaded Object:tt" + loaded);
		} catch (Exception e) {

Java serialization and version control:
The Java serialization mechanism provides an approach for version control. At the heart of Java serialization is the ObjectOutputStream class. It implements the computeSerialVersionUID() method to compute the suid during object serialization. This computed suid is then written to the serialized stream as a part of the serialized object. This suid in the stream serves as a marker to denote the version of the serializable class with which it is compatible. See Figure 2 for a sample of metadata stored in a serialized object. [Source of this text: JavaWorld]

[My Video Promotion]
  1. How to serialize Java objects into JSON format using Google’s GSON
  2. Java Object Serialization and Deserialization In MySQL Database
  3. How To Set Conditional Debug Breakpoints in Eclipse or IBM RAD?
  4. Rotating An Image In Java Graphics 2D By Specified Degree
  5. Java – How To Overlay One Image Over Another Using Graphics2D [Tutorial]
  6. Quick SQL Reference – Find Duplicate Data In A Table Using Having Clause
  7. Splitting PDF File Using Java iText API Into Multiple PDFs
  8. Object Serialization And De-Serialization In Java To Filesystem
  9. Finding Java Image Pixels Information – ARGB (Alpha, Red, Green Blue)
  10. Creating A 3D Pie Chart In Java Using JFreeChart [Example Source Code]
  11. Java Tutorial – Swing Text Drag And Drop – Sample Example
  12. Serialzing A Java Object Into XML and De-Serialzing using XMLEncoder And XMLDecoder
  13. Six Stages Of Debugging in Software Engineering
  14. Java 2D Graphics Example Tutorial On Paint, Gradient and Stroke
  15. Complete Tutorial On Using SOAP-UI to Mock Web Service Request / Response
  16. Listing The Content Of Zip File With Zip Information In Java
  17. Joke – Why do Java Programmers wear glasses?
  18. How to receive files via bluetooth in your MacBook Pro
  19. Calculating Folder Size Graphically and Generating Directory Size Chart In Java
Tagged , , , , , , , . Bookmark the permalink.

6 Responses to Calculating Folder Size Graphically and Generating Directory Size Chart In Java

  1. nocdib says:

    Thank you for this! It is just what I need

  2. d says:

    would that help you tocreate the file from ubunt server

  3. komal gaikwad says:

    in this code i got problem of array out of bound plz tell me solution.

  4. komal gaikwad says:

    In this code i got error
    Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 1
    plz send me proper code….

  5. Neethu says:

    Thank you very much for the solution. This is the one which i was searching.

  6. Manikant says:

    I need to copy to the shared folder which is shared and can be authenticate by using credentials.

    but here the code is giving to write .

    I need copy my folder from my local to shared location

    Please help

Leave a Reply to Manikant Cancel reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.