Friday, 14th October 2011
Follow WikiJava on twitter now. @Wikijava

Serialize.java

From WikiJava

Jump to: navigation, search


This example shows how to save a serializable object into a file and then retrieve it.

Contents

the article

Image:250px-Subversion.png
You can download the complete code of this article from the Subversion repository at this link

Using the username:readonly and password: readonly

See the using the SVN repository instructions page for more help about this.

A class, to be serializable must implement the interface java.io.Serializable.

like this:

public class Serialize implements Serializable

The java.io.Serializable interface doesn't implement any method, it basically doesn't do anything, it's just a marker to tell the serialization API that the class can be serialized. The serialization API can't serialize a class that is not marked serializable in this way.

When serializing an object the Serialization API, recursively tries to serialize also all the objects contained in it. This means that also all the fields of the class must be serializable, otherwise you will get the java.io.NotSerializableException.

If you really need to have not serializable classes (the ones which don't implement java.io.Serializable) in your serializable one, then these fields must be declared transient, which tells the JVM not to try to serialize that field.

Being the serializable class:

  1. implementing java.io.Serializable
  2. not containing any (non transient) not serializable objects in its fields
it can be serialized without problems. 

The way to serialize it is to use the method:

void java.io.ObjectOutputStream.writeObject(Object obj) throws IOException

In the example:

oos.writeObject(toExport);

Which writes the object toExport directly on the java.io.ObjectOutputStream, which could be anything from a file, to a tcp/ip connection.

To read the object from the file (deserialize) we use:

Object java.io.ObjectInputStream.readObject() throws IOException, ClassNotFoundException

In the example:

Object object = ois.readObject();
Serialize imported = (Serialize) object;

Which reads an Object from the java.io.ObjectInputStream and then casts it to its class (that we must know and get correctly, not to get a java.lang.ClassCastException).

Note that (as for Java 6) the generics haven't arrived to the point of relieving us from having to perform manually the cast. This would have been anyway quite complex, we hope that the future versions of Java will extend to this point.

serialize.java

package org.wikijava.serialization;
 
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
 
public class Serialize implements Serializable {
 
    private static final long serialVersionUID = 1L;
 
    /**
     * 
     * 1: creates a serializable object, 2: writes it to a file on the disk, 3:
     * reads the written file 4: outputs the object created from the file
     * 
     * @param args
     * @throws FileNotFoundException
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public static void main(String[] args) throws FileNotFoundException,
	    IOException, ClassNotFoundException {
	Serialize toExport = new Serialize();
	String filename = "serializedVersion";
 
	// writes the object to file
	writeToFile(toExport, filename);
 
	// reads a new object from file
	Serialize imported = readFromFile(filename);
 
	// output results.
	System.out.println("serializableField : "
		+ imported.getSerializableField());
 
    }
 
    /**
     * loads the object from a file
     * 
     * @param filename
     *            the filename containing the object
     * @return the imported object
     * @throws IOException
     * @throws FileNotFoundException
     * @throws ClassNotFoundException
     */
    private static Serialize readFromFile(String filename) throws IOException,
	    FileNotFoundException, ClassNotFoundException {
	// open the file
	FileInputStream fis = new FileInputStream(filename);
	ObjectInputStream ois = new ObjectInputStream(fis);
 
	// read the object
	Object object = ois.readObject();
	Serialize imported = (Serialize) object;
 
	// close the file
	ois.close();
 
	return imported;
    }
 
    /**
     * saves the object to a file
     * 
     * @param toExport
     *            the object to export
     * @param filename
     *            the filename to export to
     * @throws IOException
     * @throws FileNotFoundException
     */
    private static void writeToFile(Serialize toExport, String filename)
	    throws IOException, FileNotFoundException {
	// open the file
	FileOutputStream fos = new FileOutputStream(filename);
	ObjectOutputStream oos = new ObjectOutputStream(fos);
 
	// write the object
 
	oos.writeObject(toExport);
	oos.flush();
 
	// close the file
	oos.close();
    }
 
    private String serializableField;
 
    /**
     * CONSTRUCTOR
     */
    public Serialize() {
	this.serializableField = "serializableString";
    }
 
    public String getSerializableField() {
	return this.serializableField;
    }
 
    public void setSerializableField(String serializableField) {
	this.serializableField = serializableField;
    }
 
}

Comments from the users

To be notified via mail on the updates of this discussion you can login and click on watch at the top of the page


Comments on wikijava are disabled now, cause excessive spam.