Hi for all again and today i will write here something about the File Class, how to create, read and write data into a file and store it in local machine.

Well, yesterday i had the problem to create a file log on an AIR project, for two hours i read some articles and sample chapters about File class and only today (now, 9 April @12:15) i resolve this problem: create a class to create and write data into the File.

The code sample is:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import com.dLibs.air.recFile;
 
var nFile:recFile = new recFile();
nFile.setDiretory = "diretoryName";
 
// fileText is a textfield
fileText.text = "";
 
// saveButtom is a movieClip
saveButtom.addEventListener(MouseEvent.CLICK, saveTheFile);
 
function saveTheFile(m:MouseEvent):void
{
	var theDate:Date = new Date();
	var dateNow:String = String(theDate.getHours() + ":" + theDate.getMinutes() + ":" + theDate.getSeconds());
	var textBox:String = String(dateNow + " : " + fileText.text + "\n");
	nFile.writeData = textBox; // result sample: 13:08:32 : content of the textbox
	fileText.text = "";
}

The default format of the file is HTM, but you can change it too using the first argument of the constructor like show bellow:

3
var nFile:recFile = new recFile(“txt”);

Well, to save the data you need call the public set function writeData, see line 17. The string that you send to writeData function will be write at the last line, case document type is HTM or HTML, or after the last character for other document types.

Fine, but where my file? Hmmm, see it. Using the complete constructor arguments you can set the document type, the folder that you want save the file and too the name of the document. No one of these arguments is necessary to create the file, by default the document will be save using type HTM, saved in the Desktop, but you can change to Documents folder for Mac and My Documents for Windows, and the last, name of the file will be the date: dd_mm_yyyy.

Other set function that you can use is the setDiretory. If you chosse to create the file into the Documents folder with extension txt and there you want create other folder with the name of the your AIR project, what you can do to make it ? It’s so simple:

var nFile:recFile = new recFile(“txt”,"documents");
nFile.setDiretory = "projectName"

This today will create a file named 09_Apr_2009.txt into your My Documents / projectName folder automatically, if there have this file you will write the data at the last line of this.

You can download the full source code using the download bellow, or you can download only the classes using the SVN client: http://asdatalibs.googlecode.com/svn/trunk/

Download: Create, read and write file using AIR (231)