Technology blog oriented towards good design and impressive web applications.

IdleTogether Home

Class to Save object(s) to file with Flex in Air

by Nicolas Noben

The class

Feel free to use it for free or commercial projects.

package com.idletogether
{
	import flash.events.Event;
	import flash.filesystem.*;

	public class Saver
	{
		public static var file:File;

		public static function saveToFile() :void
		{
			// pick an unused extension
			file = new File("/filename.ext");
			file.addEventListener(Event.SELECT, dirSelected);
			file.browseForSave('');
		}

		public static function dirSelected(e:Event) :void
		{
			// this object will get saved to the file
			var dat:Object = new Object();

			dat.data = some.object;
			dat.structure = some.other.object;

			var fileStream:FileStream = new FileStream();
			fileStream.open(file, FileMode.WRITE);
			fileStream.writeObject(dat);
			fileStream.close();
		}
	}
}

How to use it

It’s a static method to be called so, simply…

import com.idletogether.Saver;
Saver.saveToFile();

This will prompt the user to pick a destination and will suggest the file name “filename.ext”.

Please note that you can’t save DisplayObjects straight to file using writeObject. It’s a limitation.

From here, find out how to get the object back into flex in the next post.

HTH,
Cheers.



Related Posts





2 Responses


  1. mark Says:

    What is some for:

    dat.data = some.object;
    dat.structure = some.other.object;

    How to use the “some”?

    Thanks

    Mark

  2. Nicolas Noben Says:

    Hey Mark,

    ’some’ is whatever object you want to save. Think of it as myObject.

    dat.structure = myStructureObject.

    So that could be a XML, pretty sure, or Array, or String… Just not a DisplayObject (such as Button).

    n

Leave a Comment







  Please note: Comments are reviewed before going public.