Monday, March 21, 2011

Files and directories in AIR: Part 11

Today we will learn how to add data to a file without overwriting it.

Say, you need to create a log of some sort. You want the user to be able to enter some text for his log entry and add it to the rest of the entries. All the data will be stored in a file, and each time the user make a new log - it is added to the file. How do we just add the log without having to overwrite the whole file?

We can use the FileMode.APPEND for that.

Let's get started. Create an AIR document and add a button and an input text field on stage. Call the button myWriteButton and the text field myText.

The first thing we do is add the listener for the button:

myWriteButton.addEventListener(MouseEvent.CLICK, writeEntry);

The whole code to make the log feature work will be in that MouseEvent function. When the user clicks the button, we need to create a new File object with a reference to the place that our log is stored at. We also need to create a new FileStream.

function writeEntry(evt:MouseEvent):void
{
var myFile:File = File.documentsDirectory.resolvePath("Air Examples/mylog.txt");
var myStream:FileStream = new FileStream();

Next, we need to prepare the String we're going to add to the text file. We will add the today's date to the log beginning, and separate the lines using File.lineEnding.

var logString:String = "Log entry " + new Date() + File.lineEnding + myText.text + File.lineEnding + File.lineEnding;

Now, we APPEND our string to the file.

myStream.open(myFile, FileMode.APPEND);
myStream.writeUTFBytes(logString);
myStream.close();
}

Full code:

import flash.filesystem.File;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import flash.events.MouseEvent;

myWriteButton.addEventListener(MouseEvent.CLICK, writeEntry);

function writeEntry(evt:MouseEvent):void
{
var myFile:File = File.documentsDirectory.resolvePath("Air Examples/mylog.txt");
var myStream:FileStream = new FileStream();
var logString:String = "Log entry " + new Date() + File.lineEnding + myText.text + File.lineEnding + File.lineEnding;
myStream.open(myFile, FileMode.APPEND);
myStream.writeUTFBytes(logString);
myStream.close();
}

Thanks for reading!

Related:

Files and directories in AIR: Part 1
Files and directories in AIR: Part 2
Files and directories in AIR: Part 3
Files and directories in AIR: Part 4
Files and directories in AIR: Part 5
Files and directories in AIR: Part 6
Files and directories in AIR: Part 7
Files and directories in AIR: Part 8
Files and directories in AIR: Part 9
Files and directories in AIR: Part 10
Create a log application using XML and AIR: Part 1
Create a log application using XML and AIR: Part 2
Create a log application using XML and AIR: Part 3
Create a log application using XML and AIR: Part 4
Files and directories in AIR: Part 12

No comments:

Post a Comment