Thursday, February 21, 2008

AIR: Get filtered list of files from filesystem

Task definition: Get list of files from specified location on the desktop or on the web which mathc certain filename pattern. In case of web you have to provide mechanism using HTTPService object. This example demonstrates AIR (desktop) version.

import flash.filesystem.File;

/** File in format: 4 to 8 digits of the name and 2 digits of the extension */
private var diagFilenamePattern:RegExp = /\d{4,8}\.\d{2,2}/g;

public function init():void {
var fileName:String = '';
var diagDir:File = new File();
diagDir.nativePath = "C:\\projects\\test_data"; // change to your directory
var origDiagFiles:Array = diagDir.getDirectoryListing();
var filteredDiagFiles:Array = new Array();
for each (var file:File in origDiagFiles) {
fileName = file.nativePath;
fileName = fileName.substring( fileName.lastIndexOf(File.separator)+1, fileName.length);
trace(fileName);
if (fileName.match(diagFilenamePattern).length) { // check if pattern match
filteredDiagFiles.push(file);
}
}
trace(origDiagFiles.length);
trace(filteredDiagFiles.length);
}

Source code is available here.