File and Folder (classes)

Categories:File

Overview

Summary

The File and Folder classes allow you to work with files and folders in an intuitive, object-oriented manner, rather than using the FLfile class and its typically verbose API.

For core file loading, see the xjsfl.file object.

Contents

Common properties and methods
File (class)
Folder (class)

Features

API

The Filesystem API is intuitive and clear, and commands can be chained together as in this short example which creates, writes, copies, appends, and opens a text file:

var file = new File('temp/test.txt', 'Hello there');
file
	.copy('temp/test copy.txt')
	.write(', and how are you today?', true)
	.open();
URI juggling

In addition, both classes support URI juggling, providing the following benefits:

  • Absolute or relative paths can be used
  • Platform or URI-format paths can be used
  • Relative paths are resolved to the xJSFL root
  • Folder {placeholder} variables are replaced
  • Windows backslashes are replaced with forward slashes
  • Erroneous multiple slashes are replaced with single slashes
  • Ancestor  paths (../) are resolved
Instantiation

Note that instantiating a File or Folder class with the new operator does NOT automatically create or modify the object on the hard disk unless a second argument is supplied:

  • in the case of File, some data to save
  • in the case of Folder, a Boolean flag to create the Folder

This allows you to create references to files or folders without modifying your hard disk.

Common properties and methods

Both the File and Folder classes have the following base properties and methods:

Properties:
Methods:

Common properties

Location

uri

The uri-formatted location of the File or Folder

  • Type: String
  • Access: Read-only

The following example traces the item's URI (note that a physical File or Folder does not need to exist to return a URI):

trace(new File('temp/some file.txt').uri);
file:///E|/Projects/xJSFL/user/jsfl/temp/some%20file.txt

path

The platform-specific path of the File or Folder

  • Type: String
  • Access: Read-only

The following example traces the item's platform-specific path (note that a physical File or Folder does not need to exist to return a path):

trace(new File('temp/some file.txt').path);
E:/Projects/xJSFL/user/jsfl/temp/some file.txt

name

The name of the File or Folder

  • Type: String
  • Access: Read-only

The following example traces the item's platform-specific path (note that a physical File or Folder does not need to exist to return a path):

trace(new File('temp/some file.txt').name);
some file.txt

parent

The object's parent folder, or the same folder if the root

  • Type: Folder
  • Access: Read-only

The following example instantiates a File object, then displays its parent (always a Folder):

var file = new File('temp/test.txt');
trace(file.parent);
[object Folder name="temp" id="temp" items=3]

Attributes

exists

true if the File or Folder exists; false otherwise.

  • Type: Boolean
  • Access: Read-only

Files or Folders can be instantiated in code, but do not return an exists flag unless:

  • The item already exists on the hard drive
  • Data is saved to the File

The following example demonstrates a new File not existing until data is saved:

var file = new File('temp/test.txt');
trace(file.exists);

file.save();
trace(file.exists);
false
true

attributes

A string specifying values for the attribute(s) you want to set

  • Type: String
  • Access:Read and write
  • N: No specific attribute
  • A: Ready for archiving (Windows only)
  • R: Read-only (on the Macintosh, read-only means “locked”)
  • W: Writable (overrides R)
  • H: Hidden (Windows only)
  • V: Visible (overrides H, Windows only)

See FLfile.setAttributes for more information.

The following example creates and writes to a new File, then makes it read-only and attempts to write to it again (see File write for more info):

// instantiiate and save a new File
	var file = new File('temp/test.txt');
	var result = file.write('Hello');
	trace(file.contents, file.attributes, result);

// make the file read only, and attempt to write to it
	file.attributes = 'RA';
	var result = file.write('Goodbye');
	trace(file.contents, file.attributes, result);		
Hello, A, [object File name="test.txt"]
Hello, RA, false

Dates

created

The number of seconds that have elapsed between January 1, 1970 and the time the file or folder was created

  • Type: Number
  • Access: Read-only

Example:

var file = new File('temp/test.txt');
trace(file.created);
1311444313		

modified

The number of seconds that have elapsed between January 1, 1970 and the time the file or folder was last modified

  • Type: Number
  • Access: Read-only

Example:

var file = new File('temp/test.txt');
trace(file.modified);
1311444313

createdDate

A JavaScript Date object that represents the date and time when the specified file or folder was created

  • Type: Date
  • Access: Read-only

Example:

var file = new File('temp/test.txt');
trace(file.createdDate);
Sat Jul 23 2011 19:06:16 GMT+0100 (GMT Daylight Time)

modifiedDate

A JavaScript Date object that represents the date and time when the specified file or folder was last modified

  • Type: Date
  • Access: Read-only

Example:

var file = new File('temp/test.txt');
trace(file.modifiedDate);
Sat Jul 23 2011 19:06:16 GMT+0100 (GMT Daylight Time)

Common methods

remove(skipConfirmation)

Deletes the File or Folder from the filesystem

Parameters:

  • skipConfirmation Boolean An optional boolean to skip the user-confirmation window

Returns:

  •   Boolean A Boolean indicating if the item was deleted or not

The following example creates a reference to the test file, then displays a confirmation box to remove the file:

var file = new File('temp/test.txt');
file.remove();	

reveal()

Reveals and selects the File or Folder in the Explorer or Finder

Returns:

  •   File The original File or Folder

The following example reveals and selects a test file in the Explorer or Finder:

var file = new File('temp/test.txt')
file.reveal();

toString(path)

A string representation of the File or Folder

Parameters:

  • path Boolean A flag to show the full path, not just the name

Returns:

  •   String A string containing the class and nam or path

The following example displays a short summary of a test file:

var file = new File('temp/test.txt');
trace(file);
[object File name="test.txt"]		

The following example displays a longer summary of the same file using the path, rather than the name:

var file = new File('temp/test.txt');
trace(file.toString(true));
[object File path="E:/Projects/xJSFL/temp/test.txt"]

File (class)

The File class is used to directly access, modify, and manipulate files on the hard disk. It has the following properties and methods:

Constructor
Properties
Methods

File(pathOrUri, contents, force)

File class

Parameters:

  • pathOrUri String The uri or path to the object
  • contents String An optional string contents of the file, or true to save a blank file
  • force Boolean An optional flag to force the file to be overwritten, if its already read-only

The following example creates a reference only to a test file:

var file = new File('temp/test.txt');

The following example creates a reference and saves some data to the test file on the hard disk, creating the file if it doesn't exist, and overwriting the file if it does:

var file = new File('temp/test.txt', 'Hello World!');

Note that creating a new File() reference with a URI that points to an existing file will affect the existing file. If you need to check if a file exists before modifying it, check the file exists property.

The following example demonstrates creating a file in a folder that doesn't exist:

var file = new File('temp/this/is/a/new/file.txt', 'It worked!');
trace(file.toString(true), file.contents);
[object File path="E:/Projects/xJSFL/user/jsfl/temp/this/is/a/new/file.txt"], It worked!

File properties

contents

Get or set the contents of the file

  • Type: String
  • Access: Read and write

The contents property is readable and writable, making it super easy to get and set the contents of files.

The following example writes a new string to a file, then reads the result back:

var file = new File('temp/contents.txt');
file.contents = 'I am a new file!');
trace(file.contents, file.createdDate);
I am a new file!, Sat Jul 23 2011 21:06:18 GMT+0100 (GMT Daylight Time)	

extension

Get the extension of the file

  • Type: String
  • Access: Read-only

The following example creates a file and traces the extension:

var file = new File('temp/test.txt');
trace(file.extension);
txt

size

Get the size of the file

  • Type: Number
  • Access: Read-only

The following example creates a file and traces its size:

var file = new File('temp/empty.txt').save();
trace(file.size);
0

writable

Set or get the read-only state of the file

  • Type: Boolean
  • Access: Read and write

The following example demonstrates writing to a file, and the various results of write(), written, and saved:

// clear the existing file
var file = new File('writable.txt', '', true);

// create the new (unsaved) file reference
var file = new File('writable.txt');

// check contents
file.writable = false;
var written = file.write('Hello!');

// results
trace('Writing to unwritable file...');
trace('contents: ' + file.contents);
trace('writable: ' + file.writable);
trace('written : ' + written);
trace('saved: ' + file.saved);

// set unwritable and attempt to write
file.writable = true;
var written = file.write('Goodbye!');

// results
trace('\nWriting to writable file...');
trace('contents: ' + file.contents)
trace('writable: ' + file.writable);
trace('written : ' + written);
trace('saved: ' + file.saved);
Writing to unwritable file...
contents:
writable: false
written : false
saved:    false

Writing to writable file...
contents: Goodbye!
writable: true
written : [object File   path="E:/Projects/xJSFL/dev/writable.txt" exists="true"]
saved:    true

saved

Flag if the file has been saved

  • Type: Boolean
  • Access: Read

See the example above for the saved property in action.

File methods

open()

Opens the file in the associated application

Returns:

  •   File The original file

Depending on the file extension the following action will be taken:

  • fla - The file will be opened in the Flash as a Document
  • jsfl - The file will be opened in Flash as a Script
  • other - The file will be opened using the OS

The following example opens an .fla file in Flash:

new File(xjsfl.uri + 'modules/Code Examples/assets/fla/example assets.fla').open();

run()

Executes any JSFL file, or attempts to run any other file type via the OS

Returns:

  •   File The original file

The run method is used to execute a file using the operating system associations. This can be used to open such files as text files, ActionScript files, or Excel documents.

Note that running this command via either Komodo or Flash before the application is open, will lock the calling application until the target application is closed (on Windows at least).

The following example creates, saves, and runs a CSV file:

new File('temp/figures.csv', 'a,b,c,d,e\r\n1,2,3,4,5').run();

copy(uriCopy, overwrite)

Copies the file to a new location

Parameters:

  • uriCopy String The new uri to copy the file to. Can be a folder or file.
  • overwrite Boolean Optional Boolean indicating whether the target file should be overwritten if it exists, defaults to false

Returns:

  •   File A new File object if the operation was successful

The following example copies a source file to a new folder (created automatically) and renames it:

var src = new File('temp/test.txt', 'Hello World!');
var trg = src.copy('temp/copied/test copy.txt');
trace(trg, trg.contents);
[object File name="test.txt"], Hello		

write(data, append)

Write or append data to the file

Parameters:

  • data String The data to append to the file
  • append Boolean An optional flag to append, rather than overwrite the file

Returns:

  •   File The original file
  •   Boolean A Boolean false if the operation failed

The following example creates a file, then writes data to it:

var file = new File('temp/test.txt');
file.write('this is a new file');

trace(file.contents);
this is a new file

append(data)

Append data to the file

Parameters:

  • data String The data to append to the file

Returns:

  •   File The original file
  •   Boolean A Boolean false if the operation failed

The following example creates a file, then appends data to it in a series of operations:

var file = new File('temp/test.txt');
var words  = 'this is a new file'.split(' ');

for each(var word in words)
{
    file.append(word + '-');
}

trace(file.contents);
this-is-a-new-file-

save()

Saves the file

Returns:

  •   File The original file

The following example creates and saves a blank file:

new File('temp/blank.txt').save();

Folder (class)

The Folder class is used to directly access, modify, and manipulate files on the hard disk. It has the following properties and methods:

Constructor
Properties
Methods

Folder(pathOrUri, create)

Folder class

Parameters:

  • pathOrUri String The uri or path to the object

The following example creates a reference only to a test folder:

var folder = new Folder('temp/new folder');

The following example creates a reference and creates a new folder:

var folder = new Folder('temp/new folder', true);	

Note that you can create entire path structures just by supplying the full path:

var folder = new Folder('temp/this/is/a/new/folder', true);
trace(folder.toString(true));
[object Folder path="E:/Projects/xJSFL/user/jsfl/temp/this/is/a/new/folder"]		

Folder properties

contents

The folder's files and folders

  • Type: Array
  • Access: Read-only

The following example returns an Array of all File and Folder items in the temp folder:

var folder = new Folder('temp');
trace(folder.contents.join('\n'));
[object File name="contents.txt"]
[object File name="dom.txt"]
[object File name="empty.txt"]
[object File name="figures.csv"]
[object File name="readme.txt"]
[object File name="test copy.txt"]
[object File name="test.txt"]
[object Folder name="test" items=1]

folders

The folder's subfolders only

  • Type: Array
  • Access: Read-only

The following example returns an Array of all Folder items in the temp folder:

var folder = new Folder('temp');
trace(folder.contents.join('\n'));
[object Folder name="test" items=1]	

files

The folder's files only

  • Type: Array
  • Access: Read-only

The following example returns an Array of File items in the temp folder:

var folder = new Folder('temp');
trace(folder.files.join('\n'));
[object File name="contents.txt"]
[object File name="dom.txt"]
[object File name="empty.txt"]
[object File name="figures.csv"]
[object File name="readme.txt"]
[object File name="test copy.txt"]
[object File name="test.txt"]

uris

The folder's contents as a list of absoulte uris

  • Type: Array
  • Access: Read

The following example returns an Array of URI strings of items in the temp folder::

var folder = new Folder('temp');
list(folder.uris);
List: Array (depth:1, objects:0, values:8, time:0.0 seconds)
--------------------------------------------------------------------------------
array => Array
	 0: "file:///E|Projects/xJSFL/dev/temp/contents.txt"
	 1: "file:///E|Projects/xJSFL/dev/temp/dom.txt"
	 2: "file:///E|Projects/xJSFL/dev/temp/empty.txt"
	 3: "file:///E|Projects/xJSFL/dev/temp/figures.csv"
	 4: "file:///E|Projects/xJSFL/dev/temp/readme.txt"
	 5: "file:///E|Projects/xJSFL/dev/temp/test/"
	 6: "file:///E|Projects/xJSFL/dev/temp/test copy.txt"
	 7: "file:///E|Projects/xJSFL/dev/temp/test.txt"

length

The number of items (both files and folders) in the folder

  • Type: Number
  • Access: Read-only

The following example :

var folder = new Folder('temp');
trace(folder.length);
8

Folder methods

open()

Opens the folder in the Explorer / Finder

Returns:

  •   Folder The original Folder

This is an alias for reveal.

copy(toPathOrURI)

Copy the folder to a new uri

Parameters:

  • toUri String The URI to copy to

Returns:

  •   Folder The original folder

Note that this method currently only works on Windows machines.

The following example copies a folder to a folder called "temp 2":

var folder = new Folder('temp');
var copy = folder.copy('temp 2');
trace(copy);
[object Folder path="E:/xJSFL/dev/temp 2/" items=10 exists="true"]	

 

each(callback, scope, itemType)

Calls a function on each element in the collection

Parameters:

  • callback Function A callback function to fire on each element
  • itemType String Optionally limit the iteration to files or folders. Leave blank for all content

Returns:

  •   Array An array of Files and/or Folders

The following example iterates over the contents of the temp folder:

new Folder('temp').each( function(element, index){ trace(index, element); } );
0, [object File name="contents.txt"]
1, [object File name="dom.txt"]
2, [object File name="empty.txt"]
3, [object File name="figures.csv"]
4, [object File name="readme.txt"]
5, [object File name="test copy.txt"]
6, [object File name="test.txt"]
7, [object Folder name="this" items=1]

filter(rx)

Return a filtered array of the folder's contents, matching against the filenames

Parameters:

  • pattern RegExp A RegExp filename pattern
  • pattern String A String filename pattern, wildcards allowed

Returns:

  •   Array An array of Filesystem objects

The following example returns only the text files of a Folder:

var files = new Folder('temp').filter(/\.txt$/)
for each(var item in files)
{
	trace(item);
}
[object File name="contents.txt"]
[object File name="dom.txt"]
[object File name="empty.txt"]
[object File name="readme.txt"]
[object File name="test copy.txt"]
[object File name="test.txt"]

Comments are closed.