Adobe
Products
Acrobat
Creative Cloud
Creative Suite
Digital Marketing Suite
Digital Publishing Suite
Elements
Photoshop
Touch Apps
Student and Teacher Editions
More products
Solutions
Creative tools for business
Digital marketing
Digital media
Education
Financial services
Government
Web Experience Management
More solutions
Learning Help Downloads Company
Buy
Home use for personal and home office
Education for students, educators, and staff
Business for small and medium businesses
Licensing programs for businesses, schools, and government
Special offers
Search
 
Info Sign in
Welcome,
My cart
My orders My Adobe
My Adobe
My orders
My information
My preferences
My products and services
Sign out
Why sign in? Sign in to manage your account and access trial downloads, product extensions, community areas, and more.
Adobe
Products Sections Buy   Search  
Solutions Company
Help Learning
Sign in Sign out My orders My Adobe
Preorder Estimated Availability Date. Your credit card will not be charged until the product is shipped. Estimated availability date is subject to change. Preorder Estimated Availability Date. Your credit card will not be charged until the product is ready to download. Estimated availability date is subject to change.
Qty:
Purchase requires verification of academic eligibility
Subtotal
Review and Checkout
Adobe Developer Connection / Adobe AIR Developer Center / AIR Quick Starts for ActionScript developers /

Building a text-file editor

by Robert L. Dixon

Robert L. Dixon
  • Content architect
  • Adobe

Modified

10 June 2010

Page tools

Share on Facebook
Share on Twitter
Share on LinkedIn
Bookmark
Print
Adobe AIR Flash Professional

Requirements

Prerequisite knowledge

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

User level

Intermediate

Required products

  • Adobe AIR
  • Flash Professional (Download trial)

Sample files

  • TextEditorFlash.zip
  • TextEditorFlash.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.

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.

Products

  • Acrobat
  • Creative Cloud
  • Creative Suite
  • Digital Marketing Suite
  • Digital Publishing Suite
  • Elements
  • Mobile Apps
  • Photoshop
  • Touch Apps
  • Student and Teacher Editions

Solutions

  • Digital marketing
  • Digital media
  • Web Experience Management

Industries

  • Education
  • Financial services
  • Government

Help

  • Product help centers
  • Orders and returns
  • Downloading and installing
  • My Adobe

Learning

  • Adobe Developer Connection
  • Adobe TV
  • Training and certification
  • Forums
  • Design Center

Ways to buy

  • For personal and home office
  • For students, educators, and staff
  • For small and medium businesses
  • For businesses, schools, and government
  • Special offers

Downloads

  • Adobe Reader
  • Adobe Flash Player
  • Adobe AIR
  • Adobe Shockwave Player

Company

  • News room
  • Partner programs
  • Corporate social responsibility
  • Career opportunities
  • Investor Relations
  • Events
  • Legal
  • Security
  • Contact Adobe
Choose your region United States (Change)
Choose your region Close

North America

Europe, Middle East and Africa

Asia Pacific

  • Canada - English
  • Canada - Français
  • Latinoamérica
  • México
  • United States

South America

  • Brasil
  • Africa - English
  • Österreich - Deutsch
  • Belgium - English
  • Belgique - Français
  • België - Nederlands
  • България
  • Hrvatska
  • Česká republika
  • Danmark
  • Eastern Europe - English
  • Eesti
  • Suomi
  • France
  • Deutschland
  • Magyarország
  • Ireland
  • Israel - English
  • ישראל - עברית
  • Italia
  • Latvija
  • Lietuva
  • Luxembourg - Deutsch
  • Luxembourg - English
  • Luxembourg - Français
  • الشرق الأوسط وشمال أفريقيا - اللغة العربية
  • Middle East and North Africa - English
  • Moyen-Orient et Afrique du Nord - Français
  • Nederland
  • Norge
  • Polska
  • Portugal
  • România
  • Россия
  • Srbija
  • Slovensko
  • Slovenija
  • España
  • Sverige
  • Schweiz - Deutsch
  • Suisse - Français
  • Svizzera - Italiano
  • Türkiye
  • Україна
  • United Kingdom
  • Australia
  • 中国
  • 中國香港特別行政區
  • Hong Kong S.A.R. of China
  • India - English
  • 日本
  • 한국
  • New Zealand
  • 台灣

Southeast Asia

  • Includes Indonesia, Malaysia, Philippines, Singapore, Thailand, and Vietnam - English

Copyright © 2012 Adobe Systems Incorporated. All rights reserved.

Terms of Use | Privacy Policy and Cookies (Updated)

Ad Choices

Reviewed by TRUSTe: site privacy statement