File class

The File class allows you to read and write text files. More...

The T/HIS JavaScript API provides many class constants, properties and methods. For Arup to be able to extend and enhance the API in the future any constant, property or method names beginning with a lowercase or uppercase letter are reserved.
If you need to add your own properties or methods to one of the existing classes then to avoid any potential future conflict you should ensure that the name begins with either an underscore (_) or a dollar sign ($) or the name is prefixed with your own unique identifier.
For example if company 'ABC' need to add a property called 'example' then to avoid any potential future conflict use one of:

Class functions

Member functions

File constants

Name Description
File.APPEND Flag to open file for appending
File.BINARY Flag to open file in binary mode. This will have no effect on unix/linux but for windows if a file is opened for writing with binary mode \n will not be translated to \r\n (CRLF), it will be written as \n (LF)
File.READ Flag to open file for reading
File.UTF8 Flag to open file for reading as UTF-8 encoding.
File.WRITE Flag to open file for writing

Constants for Find types

Name Description
File.DIRECTORY Find directories
File.FILE Find files

Constants for Seek types

Name Description
File.CURRENT Seek relative to current file position
File.END Seek relative to end of the file
File.START Seek relative to start of the file

File properties

Name Type Description
filename (read only) string Name of the file
mode (read only) constant Mode the file was opened with (File.READ, File.WRITE etc)

Detailed Description

The File class gives you simple functions to read and write text files. The following simple example shows how to read from the file "/data/test/file.txt" and print each line read to the dialogue box:

var f, line;

f = new File("/data/test/file.txt", File.READ);
while ( (line = f.ReadLine()) != undefined)
{
    Message(line);
}
f.Close();

The following simple example shows how to write the numbers 1 to 10 to the file "/data/test/file.txt":

var n, line;

f = new File("/data/test/file.txt", File.WRITE);
for (n=1; n<=10; n++)
{
    f.Writeln(n);
}
f.Close();

See the documentation below for more details.

Constructor

new File(filename[string], mode[constant])

Description

Create a new File object for reading and writing text files.

Arguments

  • filename (string)

    Filename of the file you want to read/write. If reading, the file must exist. If writing, the file will be overwritten (if it exists) if mode is File.WRITE, or if mode is File.APPEND it will be appended to if it exists, or created if it does not.
    When reading a file the filename can also be a URL (uniform resource locator) in which case the file will be read from the remote site. See File.Get() for more details on the format of the URL.

  • mode (constant)

    The mode to open the file with. Can be File.READ, File.WRITE or File.APPEND. For File.WRITE or File.APPEND it can also be ORed with File.BINARY if required. By default text is read and written as ASCII. To read/write text in utf-8 mode can also be ORed with File.UTF8 if required.

    Returns

    File object

    Return type

    File

    Example

    To create a new file object to read file "/data/test/file.txt"

    var f = new File("/data/test/file.txt", File.READ);

    Details of functions

    Close()

    Description

    Close a file opened by a File object.

    Arguments

    No arguments

    Returns

    No return value

    Example

    To close File object f.

    f.Close();


    Copy(source[string], dest[string]) [static]

    Description

    Copies a file

    Arguments

  • source (string)

    Source filename you want to copy.

  • dest (string)

    Destination filename you want to copy source file to.

    Returns

    true if copy successful, false otherwise.

    Return type

    Boolean

    Example

    To copy the file "/data/test/file.key" to "/data/test/file.key_backup"

    var copied = File.Copy("/data/test/file.key", "/data/test/file.key_backup");


    Delete(filename[string]) [static]

    Description

    Deletes a file

    Arguments

  • filename (string)

    Filename you want to delete.

    Returns

    true if successful, false if not.

    Return type

    Boolean

    Example

    To delete the file "/data/test/file.key"

    var deleted = File.Delete("/data/test/file.key");


    DriveMapFilename(filename[string], format[constant]) [static]

    Description

    Changes a filename or directory name to the correct format for a specific operating system using the directory mappings (if present)

    Arguments

  • filename (string)

    Filename you want to drive map.

  • format (constant)

    The format for the file/directory name. Can be Include.NATIVE, Include.UNIX or Include.WINDOWS

    Returns

    string containing drive mapped filename

    Return type

    String

    Example

    If T/HIS has drive S: mapped to "/data" (by using the primer*drive_s, this*drive_s, d3plot*drive_s or oasys*drive_s preference)

    var mapped = File.DriveMapFilename("/data/test/file.key", Include.WINDOWS);

    mapped will be "S:\test\file.key".

    var mapped = File.DriveMapFilename("S:\\test\\file.key", Include.UNIX);

    mapped will be "/data/test/file.key".


    Exists(filename[string]) [static]

    Description

    Check if a file exists. See also File.IsDirectory() and See also File.IsFile().

    Arguments

  • filename (string)

    Filename you want to check for existance.

    Returns

    true/false

    Return type

    Boolean

    Example

    To see if the file "/data/test/file.key" exists

    if (File.Exists("/data/test/file.key")) { do something }


    FindFiles(directory[string], type (optional)[constant]) [static]

    Description

    Find any files and/or directories in a directory.

    Arguments

  • directory (string)

    Directory to look for files/directories in.

  • type (optional) (constant)

    Type of things to find. Can be bitwise OR of File.FILE and File.DIRECTORY. If omitted only files will be returned.

    Returns

    Array of filenames/directories

    Return type

    Array

    Example

    To return the filenames in the directory /data/test:

    var fileList = File.FindFiles("/data/test")

    To return the directories in the directory /data/test:

    var fileList = File.FindFiles("/data/test", File.DIRECTORY)

    To return the files and directories in the directory /data/test:

    var fileList = File.FindFiles("/data/test", File.FILE|File.DIRECTORY)


    FindLineContaining(contain[string])

    Description

    Reads a line from a file which contains contain, opened for reading by a File object. Although this is possible using core JavaScript functions this function should be significantly faster as most of the processing is done by PRIMER in C rather than in the JavaScript interpreter. To enable this function to be as fast as possible a maximum line length of 512 characters is used. If you expect a file to have lines longer than 512 characters then use ReadLongLine which allows lines of any length. If one argument is used then the line must contain that string. If more than one argument is used then lines which contain any of the arguments will be returned

    Arguments

  • contain (string)

    String which matching lines must contain

    This argument can be repeated if required
    Alternatively a single array argument containing the multiple values can be given

    Returns

    string read from file or undefined if end of file

    Return type

    String

    Example

    Loop, reading lines from File object f which contain 'example'.

    var line;
    
    while ( (line = f.FindLineContaining("example") ) != undefined)
    {
    }
          


    FindLineStarting(start[string])

    Description

    Reads a line from a file which starts with start, opened for reading by a File object. Although this is possible using core JavaScript functions this function should be significantly faster as most of the processing is done by PRIMER in C rather than in the JavaScript interpreter. To enable this function to be as fast as possible a maximum line length of 512 characters is used. If you expect a file to have lines longer than 512 characters then use ReadLongLine which allows lines of any length. If one argument is used then the line must start with that string. If more than one argument is used then lines which start with any of the arguments will be returned

    Arguments

  • start (string)

    String which matching lines must start with

    This argument can be repeated if required
    Alternatively a single array argument containing the multiple values can be given

    Returns

    string read from file or undefined if end of file

    Return type

    String

    Example

    Loop, reading lines from File object f which start 'example'.

    var line;
    
    while ( (line = f.FindLineStarting("example") ) != undefined)
    {
    }
          


    Flush()

    Description

    Flushes a file opened for writing by a File object.

    Arguments

    No arguments

    Returns

    No return value

    Example

    To flush File object f.

    f.Flush();


    Get(url[string], filename[string], options (optional)[object]) [static]

    Description

    Get a file from a remote location. See also File.Proxy(), File.ProxyPassword() and File.ProxyUsername().

    Arguments

  • url (string)

    URL (uniform resource locator) of remote file you want to get. Currently http and ftp are supported. For http give the full address including the leading 'http://'. e.g.
    'http://www.example.com/file.html'.
    For ftp an optional username and password can be given. e.g.
    'ftp://ftp.example.com' retrieves the directory listing for the root directory.
    'ftp://ftp.example.com/readme.txt' downloads the file readme.txt from the root directory.
    'ftp://user:password@ftp.example.com/readme.txt' retrieves the readme.txt file from the user's home directory.

  • filename (string)

    Filename you want to save the file to.

  • options (optional) (object)

    Options for get. If 'username' and 'password' are set then basic authorization using the username and password will be used.

    Object has the following properties:

    Name Type Description
    password (optional) string Password
    response (optional) boolean If set to true, then the response code will be returned instead of true/false. This can be used to retieve error messages and codes when the file is not returned successfully.
    username (optional) string Username

    Returns

    true if file was successfully got, false otherwise.

    Return type

    Boolean

    Example

    To get the file "http://www.example.com/file.html" and save it to C:\temp:

    File.Get("http://www.example.com/file.html", "C:\temp\file.html");


    IsAbsolute(filename[string]) [static]

    Description

    Check if a filename is absolute or relative.

    Arguments

  • filename (string)

    Filename you want to check.

    Returns

    true/false

    Return type

    Boolean

    Example

    To see if the filename "/data/test" is absolute (which it is!)

    if (File.IsAbsolute("/data/test")) { do something }


    IsDirectory(filename[string]) [static]

    Description

    Check if a filename is a directory. See also File.Exists(), File.IsFile(), File.IsReadable() and File.IsWritable().

    Arguments

  • filename (string)

    Filename you want to check.

    Returns

    true/false

    Return type

    Boolean

    Example

    To see if the filename "/data/test" is a directory

    if (File.IsDirectory("/data/test")) { do something }


    IsFile(filename[string]) [static]

    Description

    Check if a filename is a file. See also File.Exists(), File.IsDirectory(), File.IsReadable() and File.IsWritable().

    Arguments

  • filename (string)

    Filename you want to check.

    Returns

    true/false

    Return type

    Boolean

    Example

    To see if the filename "/data/test" is a file

    if (File.IsFile("/data/test")) { do something }


    IsReadable(filename[string]) [static]

    Description

    Check if a filename has read permissions. See also File.Exists(), File.IsDirectory() and File.IsWritable().

    Arguments

  • filename (string)

    Filename you want to check.

    Returns

    true/false

    Return type

    Boolean

    Example

    To see if the filename "/data/test" is readable

    if (File.IsReadable("/data/test")) { do something }


    IsWritable(filename[string]) [static]

    Description

    Check if a filename has write permissions. If filename exists and it is a file then it is checked to see if it can be opened with write (File.APPEND permissions). If filename exists and it is a directory then the directory is checked for write permission (can files be created in the directory). If filename does not exist then it is assumed to be a file and is checked to see if it can be opened for writing (File.WRITE permissions). See also File.Exists(), File.IsDirectory() and File.IsReadable().

    Arguments

  • filename (string)

    Filename you want to check.

    Returns

    true/false

    Return type

    Boolean

    Example

    To see if the filename "/data/test" is writable

    if (File.IsWritable("/data/test")) { do something }


    Mkdir(directory[string]) [static]

    Description

    Make a directory. If PRIMER preference 'directory_permission' is set e.g.755 then this will apply (same as if set by chmod 755) ignoring any setting of umask. If there is no preference then the users current setting of umask will control permissions (same as system mkdir)

    Arguments

  • directory (string)

    The name of the directory you want to create.

    Returns

    true if successfully created, false if not.

    Return type

    Boolean

    Example

    To make the directory "/data/test"

    var success = File.Mkdir("/data/test");


    Mktemp() [static]

    Description

    Make a temporary filename for writing a temporary file.

    Arguments

    No arguments

    Returns

    String name of temporary filename that can be used.

    Return type

    String

    Example

    To get a temp filename"

    var filename = File.Mktemp();


    Proxy(name[string]) [static]

    Description

    Set a proxy for files opened by http, ftp etc. See also File.Get(), File.ProxyPassword() and File.ProxyUsername().

    Arguments

  • name (string)

    The name of the proxy.

    Returns

    No return value

    Example

    To set the proxy to "http://example.proxy.com" using port 80:

    File.Proxy("http://example.proxy.com:80");


    ProxyPassword(name[string]) [static]

    Description

    Set a proxy password for files opened by http, ftp etc. See also File.Get(), File.Proxy() and File.ProxyUsername().

    Arguments

  • name (string)

    Password for the proxy server.

    Returns

    No return value

    Example

    To set the proxy password to "password":

    File.ProxyPassword("password");


    ProxyUsername(username[string]) [static]

    Description

    Set a proxy username for files opened by http, ftp etc. See also File.Get(), File.Proxy() and File.ProxyPassword().

    Arguments

  • username (string)

    The username for the proxy.

    Returns

    No return value

    Example

    To set the proxy username to "username":

    File.ProxyUsername("username");


    ReadAll()

    Description

    Reads all the remaining characters from a file opened for reading by a File object. As this function can read the entire file as a string be careful when reading large files as it will consume large amounts of memory.

    Arguments

    No arguments

    Returns

    String. Characters read from file or undefined if end of file

    Return type

    String

    Example

    Read all characters from File object f.

     var c = f.ReadAll();


    ReadArrayBuffer(length (optional)[integer])

    Description

    Reads binary data from a file opened for reading by a File object. The data is returned as an ArrayBuffer object. For more details on how to use an ArrayBuffer see the following links:
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView.

    Arguments

  • length (optional) (integer)

    Number of bytes to try to read from the file. If omitted all the remaining data from the file will be read.

    Returns

    ArrayBuffer object or undefined if end of file

    Return type

    ArrayBuffer

    Example

    To read data as 32bit unsigned integers from File object f.

    var ab = f.ReadArrayBuffer();
    var u32 = new Uint32Array(ab);
    for (var i=0; i<u32.length; i++
    {
        var value = u32[i];
    }
          


    ReadCSV(filename[string], delimiter (optional)[string], comment (optional)[string]) [static]

    Description

    Reads the input CSV file and returns an array of string arrays. If the CSV file has legitimate records the function returns an Array object containing sub-arrays of strings otherwise the function returns NULL. The lengths of all the sub-arrays are the same and equal to maximum number of fields in any of the records. For records in a CSV file having fewer fields, the respective sub-arrays are padded with NULL elements to the maximum array length.

    Arguments

  • filename (string)

    Filename you want to read CSV options from.

  • delimiter (optional) (string)

    Delimiter string to be used. Default is a comma (",").

  • comment (optional) (string)

    Comment string to be used. Default is a dollar sign ("$").

    Returns

    2d array of strings.

    Return type

    String

    Example

    To Read CSV file "sample.csv" and print all records to a Window.

    var csv_file_path = "C:\\sample.csv";
    var records = "";
    if(!File.Exists(csv_file_path))
    {
        Window.Information("CSV file %s not present", csv_file_path);
        Exit();
    }
    var csv_array = File.ReadCSV(csv_file_path);
    if(csv_array != null)
    {
        for(var i = 0; i < csv_array.length; i++)
        {
            var record_array = csv_array[i];
            for(var j = 0; j < record_array.length; j++)
            {
                if(record_array[j] != null)
                    records = records + record_array[j] + " , ";
            }
            records = records + "\n";
        }
    }
    Options.max_window_lines = csv_array.length;
    Window.Information("File.ReadCSV Ouptut", records);
          

    To Read CSV file "sample.csv" with delimiter string "::" and comment string "##".

    var csv_array = File.ReadCSV(csv_file_path, "::", "##");
          


    ReadChar()

    Description

    Reads a single character from a file opened for reading by a File object.

    Arguments

    No arguments

    Returns

    character read from file or

    undefined

    if end of file

    Return type

    String

    Example

    Loop, reading characters from File object f.

    var c;
    
    while ( (c = f.ReadChar()) != undefined) { ... }
          


    ReadLine()

    Description

    Reads a line from a file opened for reading by a File object. To enable this function to be as fast as possible a maximum line length of 512 characters is used. If you expect a file to have lines longer than 512 characters then use ReadLongLine which allows lines of any length.

    Arguments

    No arguments

    Returns

    string read from file or

    undefined

    if end of file

    Return type

    String

    Example

    Loop, reading lines from File object f.

    var line;
    
    while ( (line = f.ReadLine()) != undefined) { ... }
          


    ReadLongLine()

    Description

    Reads a line from a file opened for reading by a File object. The line can be any length. If your file has lines shorter than 512 characters then you may want to use ReadLine instead which is faster.

    Arguments

    No arguments

    Returns

    string read from file or

    undefined

    if end of file

    Return type

    String

    Example

    Loop, reading lines from File object f.

    var line;
    
    while ( (line = f.ReadLongLine()) != undefined) { ... }
          


    Rename(oldname[string], newname[string]) [static]

    Description

    Rename an existing file to have a different name.

    Arguments

  • oldname (string)

    Existing filename you want to rename

  • newname (string)

    New filename you want to rename to

    Returns

    true if successful, false if not.

    Return type

    Boolean

    Example

    To rename the file "/data/test/file.key" to "/data/test/new_file.key"

    var size = File.Rename("/data/test/file.key", "/data/test/new_file.key");


    Seek(offset[integer], origin (optional)[constant])

    Description

    Set the current position for reading or writing in a File object.

    Arguments

  • offset (integer)

    Offset to seek to in the file

  • origin (optional) (constant)

    Origin for offset. Must be one of File.START, File.END or File.CURRENT. If omitted File.START will be used.

    Returns

    no return value

    Example

    To seek to the end of File f:

    f.Seek(0, File.END);

    To seek to the beginning of File f:

    f.Seek(0, File.START);

    To move forward 10 characters in File f:

    f.Seek(10, File.CURRENT);


    Size(filename[string]) [static]

    Description

    Return the size of a file in bytes

    Arguments

  • filename (string)

    Filename you want the size of.

    Returns

    size in bytes

    Return type

    Number

    Example

    To get the size of the file "/data/test/file.key"

    var size = File.Size("/data/test/file.key");


    Tell()

    Description

    Return the current file position for a File object. Note that on Windows when reading files if the file is not opened with File.BINARY this may not return the correct file position for files with unix line endings.

    Arguments

    No arguments

    Returns

    integer

    Return type

    Number

    Example

    To get the current file position for File f:

    var pos = f.Tell();


    Upload(filename[string], url[string], options (optional)[object]) [static]

    Description

    Uploads a file to a remote location. See also File.Proxy(), File.ProxyPassword() and File.ProxyUsername().

    Arguments

  • filename (string)

    Filename you want to upload.

  • url (string)

    URL (uniform resource locator) of the remote location you want to upload the file to. Currently only http is supported. Give the full address including the leading 'http://'. e.g.
    'http://www.example.com/file.html'.

  • options (optional) (object)

    Options for upload. If both of these are set then basic authorization using the username and password will be used.

    Object has the following properties:

    Name Type Description
    password (optional) string Password
    username (optional) string Username

    Returns

    true if file was successfully uploaded, false otherwise.

    Return type

    Boolean

    Example

    To upload the file "C:\temp\file.txt" to "http://www.example.com/file.txt":

    File.Upload("C:/temp/file.txt", "http://www.example.com/file.txt");


    Write(string[Any valid javascript type])

    Description

    Write a string to a file opened for writing by a File object. Note that a carriage return is not added.

    Arguments

  • string (Any valid javascript type)

    The string/item that you want to write

    Returns

    No return value

    Example

    To write string "Hello, world!" to File object f

    f.Write("Hello, world!\n");

    To write the title of model m to File object f

    f.Write("The title of model 2 is " + m.title + "\n");


    WriteArrayBuffer(buffer[ArrayBuffer], length (optional)[integer])

    Description

    Writes binary data to a file opened for writing by a File object. The data to write is an ArrayBuffer object. For more details on how to use an ArrayBuffer see the following links:
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView.

    Arguments

  • buffer (ArrayBuffer)

    ArrayBuffer to write to file

  • length (optional) (integer)

    Number of bytes to write to the file. If omitted all the data in the ArrayBuffer will be written (buffer.byteLength bytes)

    Returns

    No return value

    Example

    To write ArrayBuffer ab to File object f.

    f.WriteArrayBuffer(ab); 


    Writeln(string[Any valid javascript type])

    Description

    Write a string to a file opened for writing by a File object adding a carriage return.

    Arguments

  • string (Any valid javascript type)

    The string/item that you want to write

    Returns

    No return value

    Example

    To write string "Hello, world!" to File object f automatically adding a carriage return

    f.Writeln("Hello, world!");

    To write the title of model m to File object f automatically adding a carriage return

    f.Writeln("The title of model 2 is " + m.title);