File class

The File class provides functionality for reading and writing binary and text files. A File can be instantiated as an object, giving the script developer complete flexibility when reading and writing files. In addition, the File class provides a set of static convenience functions for reading and writing files in one go.

Enum AccessMode

The enum AccessMode is used in conjunction with File.open() to specify the mode in which the file is opened. The access mode is specified by OR-ing together values from the following list.

Access mode

Description

File.ReadOnly

Opens the file in read-only mode.

File.WriteOnly

Opens the file in write-only mode. If the file already exists, the file is truncated and created otherwise.

File.ReadWrite

Opens the file in read/write mode; If the file does not exist, the file will be created. If the file already exists, the file is not truncated and the write pointer starts at the end of the file while the read pointer starts at the beginning.

File.Append

Opens the file in append mode; If the file does not exist, the file will be created. If the file already exists, the file is not truncated and the write pointer starts at the end of the file.

This mode is very useful when you want to write something to a log file.

File.Translate

Enables line break translation (carriage return and linefeed) for text files to platform-specific conventions. File.Translate should only be used in combination with File.ReadOnly.

File.Truncate

If possible, the device is truncated before it is opened. All earlier content is lost.

Static functions

exists( fileName : String ) : Boolean

Returns true if fileName exists; otherwise returns false.

remove( fileName : String )

Deletes the file fileName if possible; otherwise throws an exception.

isFile( fileName : String ) : Boolean

Returns true if fileName is a file; otherwise returns false.

isDir( fileName : String ) : Boolean

Returns true if fileName is a directory; otherwise returns false.

isType( fileName : String, ext : String ) : Boolean

Returns true if the job matches the specified file type, specified as a filename extension, and false otherwise.

A file matches if its filename extension and/or its Mac file type (after conversion) match the specified filename extension. A folder matches if any of the files at the topmost level inside the folder match the specified type. These semantics are similar to those of matching cross-platform file types in filter connections.

Checking for arrival

This function checks if a file has "arrived":

hasArrived( fileName : String, stabilitySeconds : Number ) : Boolean [static]
hasArrived( stabilitySeconds : Number ) : Boolean

Returns true if it can be assumed that the file has arrived according to the heuristic describe above; otherwise returns false. The stability period is specified in seconds (as a floating point number).

The length of the required stability period depends on the nature and size of the file, on the process writing the file, and on the performance and workload of the computer system(s) involved. In most cases a stability period of 1 second is both sufficient and acceptable (in terms of delay). When the file is produced by a slow process or transferred across a slow network, a much longer stability period may be required.

A hasArrived() function often returns only after a delay of at least the stability period. However if it can be determined right away that the file has not yet arrived, the function returns immediately. Thus it is never acceptable to invoke a hasArrived() function in a tight loop.

The following table describes the two most important use cases for dealing with an external application through the hasArrived() functions. In fact, the guidance presented in the table does not depend on the employed arrival/ready detection mechanism.

Model

Description

Implementation

Synchronous

If the external process is synchronous, resource-intensive and hosted on the same computer as Switch, the jobArrived entry point should block until the process is finished (so that Switch can correctly manage the number of external processes running in parallel)

jobArrived entry point contains a waiting loop that repeatedly calls hasArrived() followed by Environment.sleep() to introduce additional delay

Asynchronous

If the external process is asynchronous (i.e. you want to feed it the next job even if the previous job hasn't been processed), if it depends on user interaction, or if it potentially takes a long time without using a lot of resources on the local computer, the jobArrived entry point should return immediately and leave the follow-up to the timerFired entry point

timerFired entry point simply calls hasArrived() once, since it is automatically executed repeatedly with a predefined interval

toNativeSeparators( fileName : String ) : String [static]

Returns fileName with the '/' separators converted to separators that are appropriate for the underlying operating system.

job.log(1, File.toNativeSeparators("this/is/a\\test"));
//"this/is/a/test" on Macintosh
//"this\is\a\test" on Windows
fromNativeSeparators( fileName : String ) : String [static]

Returns fileName using '/' as file separator.

job.log(1, File.fromNativeSeparators("this/is/a\\test"));
//"this/is/a/test"

Static Text I/O functions

read( fileName : String, codec : String ) : String

Reads and returns the contents of the file fileName if possible; otherwise throws an exception.

The optional argument codec specifies the text encoding used to read the file; see text encoding.

write( fileName : String, content : String, codec : String )

Writes the string content to the file fileName if possible (completely replacing the original contents if the file already exists); otherwise throws an exception.

The optional argument codec specifies the text encoding used to write the file contents; see text encoding.

//copies the content of the jobfile (in UTF-8) to a new path
//read the contents of the jobfile
var str = File.read(job.getPath(), "UTF-8");

//create new path
var destPath = job.createPathWithName("dest." + job.getExtension());

//write the contents to destPath
File.write(destPath, str, 'UTF-8');

//send to single outgoing connection
job.sendToSingle(destPath);

Static Binary I/O functions

The functions presented in this section read and write sequences of bytes (rather than text streams). Hence there is no need to specify a codec (see text encoding).

readByteArray( fileName : String ) : ByteArray

Reads and returns the content of the file fileName if possible; otherwise throws an exception.

writeByteArray( fileName : String, content : ByteArray )

Writes the content to the file fileName if possible (completely replacing the original contents if the file already exists); otherwise throws an exception.

//example
//create a file to write a ByteArray to
var path = job.createPathWithName("ba.txt");
var f = new File(path);

//write some data to the file
f.open(File.WriteOnly);
f.writeLine("this is text.");
f.close(); 

var ba = new ByteArray("sample", "UTF-8"); 
File.writeByteArray(path, ba); //note: old contents are removed first
job.log(1, File.readByteArray(path).toString("UTF-8")); //"sample"

Constructor

File( fileName : String, codec : String )

Creates a file object with the fileName. If fileName is missing or is not a String, an exception is thrown.

The optional argument codec specifies the text encoding used to read or write the file contents; see text encoding (if codec is missing or null, the codec is set to UTF-8 on Mac and to the current ANSI code page on Windows).

var fpath = job.createPathWithName("file.txt");
var file = new File(fpath, "UTF-8");

Properties

The File object's properties are read-only.

name : String

The name of the file including the extension.

e.g.: "SampleFile.txt"

path : String

The path of the file (= folder that contains the file) .

e.g.: "C:/Users/User1/Documents" (with 'Documents' containg the file)

fullName : String

The fullName of the file, including path, name, and extension.

e.g.: "C:/Users/User1/Documents/SampleFile.txt"

baseName : String

The name of the file, excluding its path and extension.

e.g.: "SampleFile"

extension : String

The file name's extension.

e.g.: "txt"

symLink : String

The expansion of the symlink if the file is a symlink; otherwise empty.

e.g.: "C:/Users/User1/Documents/SampleFile.txt" with the file a symlink to 'SampleFile.txt'

exists : Boolean

True if the file exists; otherwise false.

readable : Boolean

True if the file is readable; otherwise false.

writable : Boolean

True if the file is writable; otherwise false.

executable : Boolean

True if the file is executable; otherwise false.

hidden : Boolean

True if the file is hidden; otherwise false.

eof : Boolean

True if reading has reached the end of the file; otherwise false.

created : Date

The creation time of the file.

lastModified : Date

The last modification time of the file.

lastRead : Date

The last time the file was read.

size : Number

The size of the file, in bytes.

codec: String

The codec being used for reading and writing the file's contents; see text encoding.

Member functions

open( accessMode : Number )

Opens the file in the mode accessMode (see enum AccessMode) if possible; otherwise throws an exception.

For example:

profile.open(File.ReadOnly);

Opens a file for reading only.

jobfile.open(File.WriteOnly|File.Translate);

Opens a file for writing and enables line break translation.

close()

Closes the file.

remove()

Deletes the file if possible; otherwise throws an exception.

seek( pos : Number ) : Boolean

Sets file current position to "pos". Returns true on success, or false if an error occurred.

pos() : Number

Returns the current position in the file. This is the position that data is written to or read from.

Member Text I/O functions

readChar() : Number

Reads one character from the file if possible; otherwise throws an exception. The character is represented as a 16-bit Unicode code point.

read() : String

Returns the entire content of the file as a string if it can be read; otherwise throws an exception.

readLine() : String

Reads one line from file if possible; otherwise throws an exception. Retains any trailing whitespace.

readLines() : String[ ]

Returns the contents of the file as an Array of strings, one for each line. Linebreaks are stripped from the strings. If the file could not be read, an exception is thrown.

writeChar( char : Number )

Writes one character to the file if possible; otherwise throws an exception. The character is represented as a 16-bit Unicode code point.

write( data : String)

Writes the String data to the file if possible; otherwise throws an exception.

writeLine( data : String )

Writes the line data to the file and adds a linebreak. If the file could not be written error is returned.

//example
//create file to write character based data to
var path = job.createPathWithName("bytes.txt");
var f = new File(path);

//open file for writing
f.open(File.WriteOnly);
//write a character
f.writeChar(102);
//write data
f.write("this is a string \n");
//write a line
f.writeLine("This is a line");
//close the file
f.close(); 
//open the file for reading
f.open(File.ReadOnly);
//read a character
job.log(1, f.readChar());
//read lines
var lines = f.readLines();
for(i = 0; i < lines.length; i++){
    job.log(1, lines[i]);
}//"this is a string", "This is a line", ""
f.close();
//reopen the file
f.open(File.ReadOnly);
var str = f.read();
var strparts = str.split(new RegExp("\n\r*"));
for(i = 0; i < strparts.length; i++){  
    job.log(1, strparts[i]);
}//"fthis is a string", "This is a line", ""

Member Binary I/O functions

The functions presented in this section ignore the file's codec (see text encoding). Never mix these binary I/O function with any of the text-oriented I/O functions on the same file. Violating this rule has unpredictable results.

readByte() : Number

Reads one byte from the file if possible; otherwise throws an exception.

writeByte( byte : Number )

Writes one byte to the file if possible; otherwise throws an exception.

//create a new file to write bytes to
var path = job.createPathWithName("bytes.txt");
var f = new File(path);

//open the file in WriteOnly mode
f.open(File.WriteOnly);
f.writeByte(78);
f.writeByte(98);
f.close();
//close the file, reopen it in ReadOnly mode
f.open(File.ReadOnly);
job.log(1, f.readByte()); //78
job.log(1, f.readByte()); //98
f.close(); //close the file
Note: A file needs to be opened with the correct AccessMode to use the member read and write functions.