Compressed Serialization

From Robowiki
Revision as of 02:18, 6 December 2007 by Voidious (talk | contribs) (moving CompressedSerialization page)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

If you ever want to store several somewhat large objects, this is probably the best way - (aside from carefully using the transient key word) - feel free to insert this code into your robots if you find yourself using up your disk space for your robot:

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

public Object readCompressedObject(String filename)
{
	try
	{
		ZipInputStream zipin = new ZipInputStream(new
		FileInputStream(getDataFile(filename + ".zip")));
		zipin.getNextEntry();
		ObjectInputStream in = new ObjectInputStream(zipin);
		Object obj = in.readObject();
		in.close();
		return obj;
	}
	catch (FileNotFoundException e)
	{
		System.out.println("File not found!");
	}
	catch (IOException e)
	{
		System.out.println("I/O Exception");
	}
	catch (ClassNotFoundException e)
	{
		System.out.println("Class not found! :-(");
		e.printStackTrace();
	}
	return null;    //could not get the object
}
 
public void writeObject(Serializable obj, String filename)
{
	try
	{
		ZipOutputStream zipout = new ZipOutputStream(
                    new RobocodeFileOutputStream(getDataFile(filename + ".zip")));
		zipout.putNextEntry(new ZipEntry(filename));
		ObjectOutputStream out = new ObjectOutputStream(zipout);
		out.writeObject(obj);
		out.flush();
		zipout.closeEntry();
		out.close();
	}
	catch (IOException e)
	{
		System.out.println("Error writing Object:" + e);
	}
}

What this basically does is compresses your serialized objects in zip files. I can't remember exactly what degree of compression I got from doing this, but it seems like it was on the order of 1/10th the file size.