Adobe AIR 实现远程文件下载到本机的类

package net.gerhut
{
    import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.net.FileReference;
	import flash.net.URLRequest;
	import flash.net.URLStream;
	
	[Event(name="complete")]
	[Event(name="ioError", type="flash.events.IOErrorEvent")]
	public class Downloader extends EventDispatcher
	{
		private const TEMP_EXT:String = ".downloading"; 
		
		public var url:String;
		public var file:String;
		
		[Bindable]
		public var percent:uint;
		
		private var urlStream:URLStream;
		private var fileStream:FileStream = null;
		
		public function Downloader(url:String, file:String)
		{
			this.url = url;
			this.file = file;
			urlStream = new URLStream();
			urlStream.addEventListener(Event.OPEN, openHandler);
			urlStream.addEventListener(ProgressEvent.PROGRESS, progressHandler);
			urlStream.addEventListener(IOErrorEvent.IO_ERROR,ioErrorHandler);
			urlStream.addEventListener(Event.COMPLETE, completeHandler);
			fileStream = new FileStream();
			fileStream.addEventListener(Event.CLOSE,closeHandler);
		}
		
		public function start():void
		{
			var f:File = new File(file); 
			if(f.exists)
			{
				percent = 100;
				trace(file + " already downloaded.");
				dispatchEvent(new Event(Event.COMPLETE));
				return;
			}
			
			urlStream.load(new URLRequest(url));
		}
		public function openHandler(event:Event):void
		{
			fileStream.openAsync(new File(file + TEMP_EXT), FileMode.UPDATE);
			urlStream.removeEventListener(Event.OPEN, openHandler);
		}
		
		private function progressHandler(event:ProgressEvent):void
		{
			while(urlStream.bytesAvailable)
				fileStream.writeByte(urlStream.readByte());
			percent = 100 * event.bytesLoaded / event.bytesTotal;
		}
		
		private function ioErrorHandler(event:IOErrorEvent):void
		{
			dispatchEvent(new IOErrorEvent(IOErrorEvent.IO_ERROR));
		}
		
		private function completeHandler(event:Event):void
		{
			percent = 100;
			fileStream.close();
			urlStream.removeEventListener(ProgressEvent.PROGRESS, progressHandler);
			urlStream.removeEventListener(Event.COMPLETE, completeHandler);
			urlStream.close();
			urlStream = null;
		}
		
		private function closeHandler(event:Event):void
		{
			new File(file + TEMP_EXT).moveTo(new File(file), true);
			trace(file + " downloaded.");
			fileStream.removeEventListener(Event.CLOSE,closeHandler);
			fileStream = null;
			dispatchEvent(new Event(Event.COMPLETE));
		}
	}
}

用法:

var downloader:Downloader = new Downloader("http://gerhut.net/", "C:\\index.html");
downloader.addEventListener(Event.COMPLETE, completeHandler);
downloader.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
downloader.start();