You need to embed a text, javascript, xml or any other raw text file in your Flex or AIR application.
Use the Embed Metadata tag using the application/octet-stream MIME type to ensure your file is included as a Class. Then instantiate your class as a generic object and invoke the toString() method on it.
At times a developer may need to embed a pure text file in his application, and does not want to load this file externally. An example use case is the inclusion of a SCORM-compliant runtime javascript bridge which an e-learning application uses to communicate with a learning management system, because in cases like this the developer may not have access or control over the methods available within the HTML wrapper.
To embed your text file, you will need to follow three steps:
The Embed Metadata tag allows you to include external content in your Flex Project. Unfortunately the default mime types supported do not include text, so we have to use the generic "application/octet-stream" type and convert our object later. In this sample code you will note that I am declaring the object type as a Class, and am declaring it as a private static constant. This ensures that the embedded unconverted text class is not accessible, and prevents the object from taking up excessive amounts of memory by only ever creating one embed instance.
[Embed("assets/text/sample.txt", mimeType="application/octet-stream")]
private static const sampleText : Class;
The second step in our embed process, and first step in our content conversion, is to instantiate the embedded class. This will cast the embedded object as a generic object type.
var textInstance : Object = new sampleText();
The generic object data type includes, among other methods, a toString() method which converts the given class instance into a String. While it is possible to parse the object as a byte array and access the text via readUTFBytes(), it is far simpler to use the preexisting method.
var convertedText : String = textInstance.toString();
This sample code demonstrates how this process may be incorporated into a Class via static getter methods allowing easy and transparent access to the embedded text. It includes two embedded text files with different extensions, also demonstrating that this embed method is type agnostic.
A working demonstration application is included in Examples.zip below.
package com.practicalflash.examples
{
public class TextEmbed
{
[Embed("assets/javascript/sample.js", mimeType="application/octet-stream")]
private static const sampleJS : Class;
public static function get javascript ( ) : String
{
var scriptInstance : Object = new TextEmbed.sampleJS();
return scriptInstance.toString();
}
[Embed("assets/text/sample.txt", mimeType="application/octet-stream")]
private static const sampleText : Class;
public static function get text ( ) : String
{
var textInstance : Object = new TextEmbed.sampleText();
return textInstance.toString();
}
}
}