Accueil > Java > Serialisation Test de bon fonctionnement

Serialisation Test de bon fonctionnement

28/01/2009

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class TestMain {

	public static void main(String[] args) {
	    // construct test object
	    ObjectA originalObj = new ObjectA();

	    testSerialization(originalObj);

	}

	public static void testSerialization (Object originalObj)
	{
	    ObjectA extractedObj = null;

	    // serialize
	    ByteArrayOutputStream out = new ByteArrayOutputStream();
	    ObjectOutputStream oos;

	    System.out.println("Trying to serialize the object...");
		try {
			oos = new ObjectOutputStream(out);
			oos.writeObject(originalObj);
			oos.close();
			System.out.println("=>> Success.");
		} catch (IOException e) {
			System.err.println("=>> Failure: "+e.getMessage());
			e.printStackTrace();
			return;
		}

	    //deserialize
	    byte[] pickled = out.toByteArray();
	    InputStream in = new ByteArrayInputStream(pickled);
	    ObjectInputStream ois;

	    System.out.println("Trying to deserialize the object...");
		try {
			ois = new ObjectInputStream(in);
		    Object obj = ois.readObject();
		    extractedObj = (ObjectA) obj;
		    System.out.println("=>> Success.");
		} catch (IOException e) {
			System.err.println("=>> Failure: "+e.getMessage());
			return;
		} catch (ClassNotFoundException e) {
			System.err.println("=>> Failure: "+e.getMessage());
			e.printStackTrace();
			return;
		}

	    // test the result
	    System.out.println("Inuring that the extracted object is equal to the original one...");
	    if (!originalObj.equals(extractedObj)) {
	    	System.err.println("=>> Failure: Objects are not equals.");
	    	return;
	    } else {
	    	System.out.println("=>> Success.");
	    }
	  }
}

Java

Les commentaires sont fermés.