Accessibility

Adobe AIR Quick Start

 

Building a text-file editor


Adobe

Robert L. Dixon

Content architect
Adobe

Created:
25 February 2008
User Level:
Intermediate, Advanced
Products:
Adobe AIR

The Text Editor sample application shows a number of features of working with files in Adobe AIR, including the following:

  • Setting up a File object to point to a file path.
  • Getting the system-specific path for the file.
  • Using the FileMode and FileStream classes to read data from the file.
  • Using the FileMode and FileStream classes to write data from the file.
  • Using events to handle asynchronous processes.

Text Editor application

Figure 1. The Text Editor sample application is a simple editor of plain text files.

Note: This is a sample application provided, as is, for instructional purposes.

Requirements

To make the most of this article, you need the following software and files:

Adobe AIR

Adobe Flash CS3 Professional

Adobe AIR Update for Flash CS3 Professional

Sample files:

This sample application includes the following files:

  • TextEditorFlash.fla: The FLA file which contains the main AIR application assets.
  • com/air/flash/TextEditorFlash.as: The ActionScript file which contains the AIR application code.
  • TextEditorFlash-app.xml: The AIR application descriptor file.
  • Sample AIR icon files

Prerequisite knowledge

General experience of building applications with Flash CS3 is suggested. For more details on getting started with this Quick Start, refer to Building the Quick Start sample applications with Flash.

Testing the application

Download and launch the application's installer (TextEditor.air) to install the application. The application is a simple editor of plain text files. The application uses UTF-8 encoding for reading and writing all text files.

Understanding the code

This article does not describe all of the ActionScript classes used in the application. For more information, see the ActionScript 3 .0 Language and Components Reference.

Pointing a File object to a file

One of the first statements in the TextEditorFlash() constructor method sets the defaultDirectory File object to the default documents directory. In Windows, this is the My Documents directory. In Mac OS, it is the /Users/userName/Documents directory.

defaultDirectory = File.documentsDirectory;

Later the openFile() method defines a fileChooser File object and sets it initially to the value of the defaultDirectory variable:

private function openFile(event:MouseEvent):void
{ 
    var fileChooser:File;
    if (currentFile) 
    {
        fileChooser = currentFile;
    }
    else
    {
        fileChooser = defaultDirectory;
    }
    fileChooser.browseForOpen("Open");
    fileChooser.addEventListener(Event.SELECT, fileOpenSelected);
}

The File.browseForOpen() method then opens a file chooser dialog box.

Reading a file

When the user selects a file in the file chooser box and clicks the OK button, the fileOpenSelected() method is called.

private function fileOpenSelected(event:Event):void
{
    currentFile = event.target as File;
    stream = new FileStream();
    stream.openAsync(currentFile, FileMode.READ);
    stream.addEventListener(Event.COMPLETE, fileReadHandler);
    stream.addEventListener(IOErrorEvent.IO_ERROR, readIOErrorHandler);
    dataChanged = false;
    currentFile.removeEventListener(Event.SELECT, fileOpenSelected);
}

The fileOpenSelected() method points the currentFile File object to the file that was selected by the user. Next a FileStream object is opened in asynchronous mode, with its fileMode parameter set to FileMode.READ, and the reading of the file begins.

Next some event handlers are set up to respond to the FileStream object’s complete and ioError events. You can add these event listeners after calling the openAsync() method because the runtime completes executing this full block of ActionScript code (including the calls to addEventListener() methods) before responding to any events.

This sample application shows how to read a file asynchronously. You can also read the file synchronously by calling the open() method when opening the file, rather than calling the openAsync() method. For more information, see “Working with the file system” on page 1.

If the stream object dispatches an ioError event, the readIOErrorHandler() displays an error message for the end user.

Reading bytes from a file

When the file has been fully read into memory, the stream object dispatches the complete event, which triggers the executions of the fileReadHandler() method.

private function fileReadHandler(event:Event):void 
{
    var str:String = stream.readUTFBytes(stream.bytesAvailable);
    stream.close();
    var lineEndPattern:RegExp = new RegExp(File.lineEnding, "g");
    str = str.replace(lineEndPattern, "\n");
    mainTextField.text = str; 
    stream.close();
}

The FileStream.readUTFBytes() method reads a specified number of bytes representing UTF-8 characters and returns a String object. The stream object just dispatched a complete event, so the bytesAvailable property represents the total length of the file.

Next a regular expression is used to replace the line ending characters from the file with the "\n" newline character which is used by ActionScriptTextField objects. The string value is stored in the mainTextField object’s text property, and then the FileStream object is closed (so the memory space it was using can be reclaimed).

Writing data to a file

The saveFile() method writes the contents of the text field to the file object specified in the currentFile variable.

private function saveFile(event:MouseEvent = null):void 
{
    if (currentFile) {
    if (stream != null) 
    {
        stream.close();
    }
        stream = new FileStream();
        stream.openAsync(currentFile, FileMode.WRITE);
	      stream.addEventListener(IOErrorEvent.IO_ERROR, writeIOErrorHandler);
	      var str:String = mainTextField.text;
	      str = str.replace(/\r/g, "\n");
	      str = str.replace(/\n/g, File.lineEnding);
	      stream.writeUTFBytes(str);
	      stream.close();
	      dataChanged = false;
    } 
    else
    {
        saveAs();
    }
}

First, the method checks to see if the currentFile object has been assigned a value yet. The currentFile object is undefined when the user first opens the application, and when the user clicks the New button. If there is no currentFile defined, then the saveAs() method is called to let the user select a new file path for saving the file.

Next the stream FileStream object is closed (in case it was already open) and then initialized.

This time the FileStream.openAsync() method is called with the fileMode parameter set to FileMode.WRITE.

An event handler is set up to respond in case an ioError event occurs.

Before saving the text data to the file, a regular expression is used to replace the "\n" newline character used in an ActionScript TextField object with the line ending character used in text files in the current file system (as defined by the File.lineEnding variable).

Finally the ileStream.writeUTFBytes() method writes the string value to the file in UTF-8 format, and then the file stream is closed.

Saving as a new file

Saving text as a new file is a two-step process. First the user selects a file path and gives the new file a name. Next the text field contents are written to the new file using the saveFile() method described above.

When the user clicks the Save As button, or when the Save button is clicked after creating a file, the saveAs() method is called.

private function saveAs(event:MouseEvent = null):void 
{
    var fileChooser:File;
    if (currentFile)
    {
	      fileChooser = currentFile;
    }
    else
    {
	      fileChooser = defaultDirectory;
    }
    fileChooser.browseForSave("Save As");
    fileChooser.addEventListener(Event.SELECT, saveAsFileSelected);
}

The saveAs() method is similar to the openFile() method. It opens a file dialog box that’s initially set to the default document directory. Then it lets the user browse to the location where the new file should be saved and enter a new file name.

When the user clicks the Save button in the dialog box, the saveAsFileSelected() method is called:

private function saveAsFileSelected(event:Event):void 
{
     currentFile = event.target as File;
     saveFile();
     dataChanged = false;
     currentFile.removeEventListener(Event.SELECT, saveAsFileSelected);
}

This method simply sets the currentFile variable to the new File object and calls the saveAs() method, described in the previous section, to save the text data to the new file.

About the author

Rob Dixon began developing Flash client/server applications in 1998 and hasn't let up since. He currently works with the Instructional Media Development group at Macromedia, where he recently developed the sample applications and cowrote the documentation for the AOL Instant Messaging SDK for Macromedia Central. He published a book on CASE software and project management many years ago, when CASE was all the rage. He also cofounded Tier Technologies Inc. in 1991 and has managed some smaller software and consulting companies since then, including Terrific Software Inc., founded in 2003. You can reach him at rdixon@macromedia.com.