File and Folder (classes)
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:
- Location: uri,path, name, parent
- Attributes: exists, attributes
- Dates: created, modified, createdDate, modifiedDate
Methods:
Common properties
Location
uri
The uri-formatted location of the File or Folder
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
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
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
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.
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
- 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
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
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
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
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
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
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
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
- open()
- run()
- copy(trgURIOrPath, overWrite)
- write(data, append)
- append(data)
- save(utf8)
- reveal()
- rename(name, extension)
- toString(name)
File(pathOrUri, contents, force)
File class
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
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
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
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
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
File methods
open()
Opens the file in the associated application
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
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
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
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
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
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
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
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
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
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
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
The following example :
var folder = new Folder('temp'); trace(folder.length);
8
Folder methods
copy(toPathOrURI)
Copy the folder to a new uri
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
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
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.