io::File class

The File class represents an open file as a stream.

class File(path, ...)
Open a file for reading and/or writing. This class is a subclass of Stream. The optional arguments may include Input, Output or Append, or a combination of these. If none of these options are specified, the file defaults to Input. Output and Append options cannot be mixed. When opening an existing file for writing using the Output option, the existing file contents will be lost and the file length will be truncated to zero. The optional arguments may also include one of the buffering options Buffered, LineBuffered or Unbuffered; if omitted, the stream defaults to fully buffered access. If the optional arguments include Protected, the file access permissions are set so that only the current user can access the file, and the file must not exist before the call. This is only applicable if the file is opened in Output mode.

File objects should be closed after they are no longer needed by calling the close method. Otherwise any system resources allocated to them may not be freed until the program exits.

Note: File objects are narrow (8-bit) streams. They do not directly support reading and writing the full Unicode character set. The file contents are interpreted as raw bytes and they are directly mapped to character codes. The TextFile class allows you to create and access files encoded in several common encodings such as UTF-8. The File class is useful for accessing file contents as raw binary data or for accessing files encoded in ASCII or ISO Latin 1.

File methods

The File class supports all the methods of the Stream class (follow the previous link for more information) and these additional methods:

seek(offset)
Seek to a specific byte offset in the file. The next read or write operation will start at this location. The first byte in the file has the offset 0.

To seek to the end of the file, use seek with size:

file.seek(file.size())
pos()
Return the current byte offset in the file. The offset 0 refers to the start of the file.
size()
Return the size of the file, in bytes.

Note: The methods seek, pos and size are supported for regular files but might not work with special files such as devices.

The File class has these internal methods that are accessed by the Stream superclass. Usually these methods are not accessed directly:

_write(...)
Write the arguments directly to the file without buffering. The arguments must be strings.
_read(size)
Read up to the specified number of bytes from the file directly without buffering.