Embed a text/txt file in a Flex/AS3 application

This is actually pretty easy, but it’s not something widely known. Here’s the code:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
            layout="absolute"
            creationComplete="trace(text);">
   <mx:Script>
      <![CDATA[
         [Embed( source="myTextFile.txt", mimeType="application/octet-stream" )]
         public var MyText:Class
         public var text:String=new MyText().toString();
      ]]>
   </mx:Script>
</mx:Application>

So what is this doing?
The embed tag works to keep the file in your swf. It then binds it to the Class defined on the next line. Since it’s an unrecognized file format (Flex supports swf, mp3, jpg, gif, png), Flex wouldn’t know what to do with it, so we specify a mimeType — a description of how to handle this file.
Then, we create a new variable and set its contents to a new instance of the Class, then convert it to a string.
Finally, I’ve set the Application parameter creationComplete to perform a trace of the text variable’s contents. If all is correct, you should see a trace with the txt file’s contents.
EmbedTXTTest

One comment

Leave a Reply

Your email address will not be published. Required fields are marked *