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 Jeff Swartz

Jeff Swartz  Adobe

Modified

10 October 2011

Page tools

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

Requirements

Prerequisite knowledge

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

User level

Intermediate

Required products

  • Adobe AIR
  • Flash Builder (Download trial)
  • Flex (Download trial)

Sample files

  • TextEditor.zip
  • TextEditor.air
  • TextEditor-fxp.zip

The Text Editor sample application is intentionally simple (see Figure 1). The intent is to show you the basics of how to work with files in Adobe AIR. More specifically you learn the following:

  • Setting up a File object to point to a file path
  • Getting the system-specific path (nativePath) for the file
  • Using the FileMode and FileStream classes to read data from the file
  • Using the FileMode and FileStream classes to write data to the file
  • Using events to handle asynchronous processes
Flex Text Editor
Figure 1. This sample application is a simple editor of plain text files.

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

This sample application includes the following files in the src directory:

  • TextEditor.mxml: The main application file in MXML for Flex; includes the code discussed in this article
  • TextEditor-app.xml: The AIR application descriptor file
  • Sample AIR icon files

Important: The application descriptor file, FileCompressionTool-app.xml, uses the AIR 3.0 namespace. To modify and repackage this application, you need to download and use AIR 3 SDK along with Flash Builder 4.5.

Testing the application

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

Understanding the code

Note: This article does not describe all of the Flex components used in the MXML code for the file. For more information, see the ActionScript 3 Reference for the Adobe Flash Platform.

Pointing a File object to a file

The appCompleteHandler() method sets the defaultFile File object to point to a pre-defined path:

defaultFile = File.documentsDirectory.resolvePath("test.txt");

This code sets the File object to point to the test.txt file in the user's documents directory. In Windows, this is the My Documents directory. In Mac OS, it is the /Users/userName/Documents directory.

The defaultFile file is later passed to Open and Save As pop-up windows, if the user has not yet selected a file path.

Reading a file

The openFile() method contains code that opens a file chooser dialog box. When the user selects a file and clicks the OK button, the fileOpenSelected() method is called. The method first initiates the file File object to point to the path specified by the user:

currentFile = event.file;

Next the stream FileStream object is closed (in case it currently has a file open) and the stream FileStream object are initialized:

if (stream != null) { stream.close(); } stream = new FileStream(); stream.openAsync(currentFile, FileMode.READ);

Note: The fileMode parameter of the openAsync() method is set to FileMode.READ. This lets you read the file.

Event handlers are set up to respond to the complete and ioError events:

stream.addEventListener(Event.COMPLETE, fileReadHandler); stream.addEventListener(IOErrorEvent.IO_ERROR, readIOErrorHandler);

AIR begins reading the file asynchronously, and the runtime automatically starts reading the file in and firing events. Note that you can add these event listeners after calling the openAsync() method, because the runtime will complete executing this ActionScript code (the block of code that includes the calls to addEventListener() methods) before responding to any events.

Note: 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.

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

When the file is read in fully, the stream object dispatches the complete event, and the fileReadHandler() method reads and processes the file.

The readUTFBytes() method of the stream object returns a string by reading UTF-8 characters from specified number of bytes. Since the stream object just dispatched the complete event, the bytesAvailable property represents the total length of the file, and it is passed as the length property of the call to the readUTFBytes() method:

var str:String = stream.readUTFBytes(stream.bytesAvailable);

The following code replaces the line ending characters from the file with the \n newline character, which is used in a TextField object in a SWF file. It then assigns the string to the text property of the Text control:

var lineEndPattern:RegExp = new RegExp(File.lineEnding, "g"); str = str.replace(lineEndPattern, "\n"); mainTextField.text = str;

Writing data to a file

The saveFile() method contains code that writes the text to the file.

First, the method checks to see if the main File object is set:

if (currentFile)

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 (in the else block), which lets the user select a file path for saving the file.

Next the stream FileStream object is closed (if it is currently open) and then it is initialized:

if (stream != null) { stream.close(); } stream = new FileStream(); stream.openAsync(currentFile, FileMode.WRITE);

Note that the mode parameter of the openAsync() method is set to FileMode.WRITE. This lets you write to the file.

An event handler is set up to respond to any ioError events:

stream.addEventListener(IOErrorEvent.IO_ERROR, writeIOErrorHandler);

The following code replaces the "\n" newline character, which is used in a TextField object in a SWF file, with the line ending character used in text files in the file system ( File.lineEnding ) It then assigns the string to the text property of the Text control:

var str:String = mainTextField.text; str = str.replace(/\r/g, "\n"); str = str.replace(/\n/g, File.lineEnding);

The writeUTFBytes() method of the stream object writes a string to the file in UTF-8 format and then closes the file:

stream.writeUTFBytes(str); stream.close();

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

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