Thursday, March 17, 2011

Files and directories in AIR: Part 7

Last time we learned how to read local files, this time we will learn how to read files from the internet.

There are two ways to open external files from the internet: using the URLLoader and URLStream classes.

The URLLoader class we can load a file completely, and only after it has been fully loaded can it be read. For example, if we are loading a picture into AIR, we will have to wait until it loads 100% before we can read anything.

The URLStream class, on the other hand, lets us read a file even when it is being loaded. For example, if we are loading a video, we can already play it while it is still loading.

In this example I am going to use the URLStream class, because it is better for reading binary files as this class is the base tool for that.

First of all, create an url request.

import flash.net.URLRequest;

var myRequest:URLRequest = new URLRequest("http://2.bp.blogspot.com/_l1TO0E4U6fA/TItZS1m58JI/AAAAAAAAAIM/buD2-nhz8ao/S150/blog_btn_2.png");

Now we need to make the URLStream object itself.

import flash.net.URLStream;

var myStream:URLStream = new URLStream();

Add a listener that calls a function once the loading of the file is fully complete:

import flash.events.Event;

myStream.addEventListener(Event.COMPLETE, loadComplete);

Start the loading process:

myStream.load(myRequest);

Read and trace each byte like this:

function loadComplete(evt:Event):void{
trace("Loading complete!");
while(myStream.bytesAvailable){
trace(myStream.readByte());
}
}

This is the full code:

import flash.net.URLRequest;
import flash.net.URLStream;
import flash.events.Event;

var myRequest:URLRequest = new URLRequest("http://2.bp.blogspot.com/_l1TO0E4U6fA/TItZS1m58JI/AAAAAAAAAIM/buD2-nhz8ao/S150/blog_btn_2.png");
var myStream:URLStream = new URLStream();
myStream.addEventListener(Event.COMPLETE, loadComplete);
myStream.load(myRequest);

function loadComplete(evt:Event):void{
trace("Loading complete!");
while(myStream.bytesAvailable){
trace(myStream.readByte());
}
}

In this example we do nothing else but trace each byte. This is, of course, will most likely never be needed, but now we know how to get access to a file that is located on the internet.

Thanks for reading!

Related:

Files and directories in AIR: Part 1
Files and directories in AIR: Part 2
Files and directories in AIR: Part 3
Files and directories in AIR: Part 4
Files and directories in AIR: Part 5
Files and directories in AIR: Part 6
Files and directories in AIR: Part 8
Files and directories in AIR: Part 9
Files and directories in AIR: Part 10
Files and directories in AIR: Part 11
Create a log application using XML and AIR: Part 1
Create a log application using XML and AIR: Part 2
Create a log application using XML and AIR: Part 3
Create a log application using XML and AIR: Part 4
Files and directories in AIR: Part 12

No comments:

Post a Comment