Skip to main content

module IO

Usage

import IO;

Synopsis

Library functions for input/output.

Description

The following input/output functions are defined:

function registerLocations

void registerLocations(str scheme, str authority, map[loc logical, loc physical] m)

Synopsis

Register a logical file scheme including the resolution method via a table.

Description

Logical source location schemes, such as |java+interface://JRE/java/util/List| are used for precise qualified names of artifacts while abstracting from their physical location in a specific part of a file on disk or from some webserver or source repository location.

Using this function you can create your own schemes. The authority field is used for scoping the names you wish to resolve to certain projects. This way one name can resolve to different locations in different projects.

Benefits

  • Logical source locations are supported by IDE features such as hyperlinks
  • Logical source locations are supported by all IO functions as well

Pitfalls

  • Repeated calls to registerLocations for the same scheme and authority will overwrite the m map.
  • The registry is an intentional memory leak; so make sure you use it wisely. See also unregister locations.
  • When the files references by the physical locations are being written to (edited, removed), then you may expect problems. The registry is not automatically invalidated.

function unregisterLocations

void unregisterLocations(str scheme, str authority)

Undo the effect of register locations

Description

For debugging or for memory management you may wish to remove a lookup table.

function resolveLocation

loc resolveLocation(loc l)

function appendToFile

void appendToFile(loc file, value V..., str charset=DEFAULT_CHARSET, bool inferCharset=!(charset?))
throws PathNotFound, IO

void appendToFile(loc file, value V..., str charset=DEFAULT_CHARSET, bool inferCharset=!(charset?))
throws PathNotFound, IO

Synopsis

Append a value to a file.

Description

Append a textual representation of some values to an existing or a newly created file:

  • If a value is a simple string, the quotes are removed and the contents are de-escaped.
  • If a value has a non-terminal type, the parse tree is unparsed to produce a value.
  • All other values are printed as-is.
  • Each value is terminated by a newline character.

The existing file can be stored using any character set possible, if you know the character set, please use append to file enc. Else the same method of deciding the character set is used as in read file.

Pitfalls

  • The same encoding pitfalls as the read file function.

function appendToFileEnc

void appendToFileEnc(loc file, str charset, value V...) throws PathNotFound, IO

Synopsis

Append a value to a file.

Description

Append a textual representation of some values to an existing or a newly created file:

  • If a value is a simple string, the quotes are removed and the contents are de-escaped.
  • If a value has a non-terminal type, the parse tree is unparsed to produce a value.
  • All other values are printed as-is.
  • Each value is terminated by a newline character.

Files are encoded using the charset provided.

function charsets

set[str] charsets()

Synopsis

Returns all available character sets.

function canEncode

set[str] canEncode(str charset)

Synopsis

Returns whether this charset can be used for encoding (use with write file)

function bprintln

bool bprintln(value arg)

Synopsis

Print a value and return true.

Description

Print a value and return true. This is useful for debugging complex Boolean expressions or comprehensions. The only difference between this function and println is that its return type is bool rather than void.

Examples

rascal>import IO;
ok
rascal>bprintln("Hello World");
Hello World
bool: true

function exists

bool exists(loc file)

Synopsis

Check whether a given location exists.

Description

Check whether a certain location exists, i.e., whether an actual file is associated with it.

Examples

rascal>import IO;
ok

Does the library file IO.rsc exist?

rascal>exists(|std:///IO.rsc|);
bool: true

function find

loc find(str name, list[loc] path) throws PathNotFound

Synopsis

Find a named file in a list of locations.

Examples

rascal>import IO;
ok

Find the file IO.rsc in the standard library:

rascal>find("IO.rsc", [|std:///|]);
loc: |std:///IO.rsc|

function isDirectory

bool isDirectory(loc file)

Synopsis

Check whether a given location is a directory.

Description

Check whether the location file is a directory.

function iprint

void iprint(value arg, int lineLimit = 1000)

Synopsis

Print an indented representation of a value.

Description

See iprintExp for a version that returns its argument as result and iprintln for a version that adds a newline and iprintToFile for a version that prints to a file.

Examples

rascal>import IO;
ok
rascal>iprint(["fruits", ("spider" : 8, "snake" : 0), [10, 20, 30]]);
[
"fruits",
("snake":0,"spider":8),
[10,20,30]
]
ok

function iprintToFile

void iprintToFile(loc file, value arg, str charset=DEFAULT_CHARSET)

Synopsis

Print an indented representation of a value to the specified location.

Description

See iprint for a version that displays the result on the console and iprintExp for a version that returns its argument as result and iprintln for a version that adds a newline.

Examples

rascal>import IO;
ok
rascal>iprintToFile(|file:///tmp/fruits.txt|, ["fruits", ("spider" : 8, "snake" : 0), [10, 20, 30]]);
ok

function iprintToString

str iprintToString(value arg)

function iprintExp

&T iprintExp(&T v)

Synopsis

Print an indented representation of a value and returns the value as result.

Description

See iprintlnExp for a version that adds a newline.

Examples

rascal>import IO;
ok
rascal>iprintExp(["fruits", ("spider" : 8, "snake" : 0), [10, 20, 30]]);
[
"fruits",
("snake":0,"spider":8),
[10,20,30]
]
list[value]: [
"fruits",
("snake":0,"spider":8),
[10,20,30]
]

function iprintlnExp

&T iprintlnExp(&T v)

Synopsis

Print an indented representation of a value followed by a newline and returns the value as result.

Description

See iprintExp for a version that does not add a newline.

Examples

rascal>import IO;
ok
rascal>iprintlnExp(["fruits", ("spider" : 8, "snake" : 0), [10, 20, 30]]);
[
"fruits",
("snake":0,"spider":8),
[10,20,30]
]
list[value]: [
"fruits",
("snake":0,"spider":8),
[10,20,30]
]

function iprintln

void iprintln(value arg, int lineLimit = 1000)

Synopsis

Print a indented representation of a value and add a newline at the end.

Description

See iprintlnExp for a version that returns its argument as result and iprint for a version that does not add a newline.

By default we only print the first 1000 lines, if you want to print larger values, either use writeTextValueFile or change the limit with the lineLimit parameter.

Examples

rascal>import IO;
ok
rascal>iprintln(["fruits", ("spider" : 8, "snake" : 0), [10, 20, 30]]);
[
"fruits",
("snake":0,"spider":8),
[10,20,30]
]
ok
rascal>iprintln([ {"hi"} | i <- [0..1000]], lineLimit = 10);
[
{"hi"},
{"hi"},
{"hi"},
{"hi"},
{"hi"},
{"hi"},
{"hi"},
{"hi"},
{"hi"},
...
ok

function isFile

bool isFile(loc file)

Synopsis

Check whether a given location is actually a file (and not a directory).

Description

Check whether location file is actually a file.

function lastModified

datetime lastModified(loc file)

Synopsis

Last modification date of a location.

Description

Returns last modification time of the file at location file.

Examples

rascal>import IO;
ok

Determine the last modification date of the Rascal standard library:

rascal>lastModified(|std:///IO.rsc|);
datetime: $2022-11-22T14:52:28.000+00:00$

function created

datetime created(loc file)

Synopsis

Creation datetime of a location.

Description

Returns the creation time of the file at location file.

Examples

rascal>import IO;
ok

Determine the last modification date of the Rascal standard library:

rascal>created(|std:///IO.rsc|);
datetime: $2022-11-22T14:52:28.000+00:00$

function touch

void touch(loc file)

Synopsis

Set the modification date of a file to now or create the file if it did not exist yet

function setLastModified

void setLastModified(loc file, datetime timestamp)

Synopsis

Set the modification date of a file to the timestamp

function listEntries

list[str] listEntries(loc file)

Synopsis

List the entries in a directory.

Description

List the entries in directory file.

Examples

rascal>import IO;
ok

List all entries in the standard library:

rascal>listEntries(|std:///|);
list[str]: ["Boolean.rsc","Content.rsc","DateTime.rsc","Exception.rsc","Grammar.rsc","IO.rsc","List.rsc","ListRelation.rsc","Location.rsc","Map.rsc","Message.rsc","Node.rsc","ParseTree.rsc","Prelude$1.class","Prelude$2.class","Prelude$3.class","Prelude$4.class","Prelude$Backtrack.class","Prelude$ByteBufferBackedInputStream.class","Prelude$Distance.class","Prelude$Less.class","Prelude$NodeComparator.class","Prelude$ReleasableCallback.class","Prelude$Sorting.class","Prelude.class","Prelude.rsc","Relation.rsc","Set.rsc","String.rsc","Type.class","Type.rsc","ValueIO.rsc","analysis","demo","index.md","lang","resource","util","vis"]

function mkDirectory

void mkDirectory(loc file)
throws PathNotFound, IO

void mkDirectory(loc file)
throws PathNotFound, IO

Synopsis

Create a new directory.

Description

Create a directory at location file.

function print

void print(value arg)

Synopsis

Print a value without subsequent newline.

Description

Print a value on the output stream. See println for a version that adds a newline and printExp for a version that returns its argument as value.

Examples

Note that the only difference with println is that no newline is added after the value is printed

rascal>import IO;
ok
rascal>print("Hello World");
Hello World
ok

NOTE: Since print does not add a newline, the prompt ok appears at a weird place, i.e., glued to the output of print.

function printExp

&T printExp(&T v)

&T printExp(str msg, &T v)

Synopsis

Print a value and return it as result.

Examples

rascal>import IO;
ok
rascal>printExp(3.14);
3.14
real: 3.14
rascal>printExp("The value of PI is approximately ", 3.14);
The value of PI is approximately 3.14
real: 3.14

function println

void println(value arg)

void println()

Synopsis

Print a value to the output stream and add a newline.

Description

Print a value on the output stream followed by a newline. See print for a version that does not add a newline and printlnExp for a version that returns its argument as value.

Examples

rascal>import IO;
ok
rascal>println("Hello World");
Hello World
ok

Introduce variable S and print it:

rascal>S = "Hello World";
str: "Hello World"
rascal>println(S);
Hello World
ok

Introduce variable L and print it:

rascal>L = ["a", "b", "c"];
list[str]: ["a","b","c"]
rascal>println(L);
["a","b","c"]
ok

Use a string template to print several values:

rascal>println("<S>: <L>");
Hello World: ["a","b","c"]
ok

Just print a newline

rascal>println();
ok

function printlnExp

&T printlnExp(&T v)

&T printlnExp(str msg, &T v)

Synopsis

Print a value followed by a newline and return it as result.

Examples

rascal>import IO;
ok
rascal>printlnExp(3.14);
3.14
real: 3.14
rascal>printlnExp("The value of PI is approximately ", 3.14);
The value of PI is approximately 3.14
real: 3.14

NOTE: Since printExp does no produce a newline after its output, the result prompt real: 3.14 is glued to the output of printExp.

function rprint

void rprint(value arg)

Synopsis

Raw print of a value.

Pitfalls

This function is only available for internal use in the Rascal development team.

function rprintln

void rprintln(value arg)

Synopsis

Raw print of a value followed by newline.

Pitfalls

This function is only available for internal use in the Rascal development team.

function readFile

str readFile(loc file, str charset=DEFAULT_CHARSET, bool inferCharset=!(charset?))
throws PathNotFound, IO

str readFile(loc file, str charset=DEFAULT_CHARSET, bool inferCharset=!(charset?))
throws PathNotFound, IO

Synopsis

Read the contents of a location and return it as string value.

Description

Return the contents of a file location as a single string. Also see read file lines.

Encoding

A text file can be encoded in many different character sets, most common are UTF8, ISO-8859-1, and ASCII. If you know the encoding of the file, please use the read file enc and read file lines enc overloads. If you do not know, we try to detect this. This detection is explained below:

  • If the implementation of the used scheme in the location (e.g.,|project:///|) defines the charset of the file then this is used.
  • Otherwise if the file contains a UTF8/16/32 BOM, then this is used.
  • As a last resort the IO library uses heuristics to determine if UTF-8 or UTF-32 could work: Are the first 32 bytes valid UTF-8? Then use UTF-8. Are the first 32 bytes valid UTF-32? Then use UTF-32.
  • Finally, we fall back to the system default (as given by the Java Runtime Environment).

To summarize, we use UTF-8 by default, except if the location has available meta-data, the file contains a BOM, or the first 32 bytes of the file are not valid UTF-8.

Pitfalls

  • In case encoding is not known, we try to estimate as best as we can.
  • We default to UTF-8, if the file was not encoded in UTF-8 but the first characters were valid UTF-8, you might get an decoding error or just strange looking characters.

function readFileEnc

str readFileEnc(loc file, str charset) throws PathNotFound, IO

Synopsis

Read the contents of a location and return it as string value.

Description

Return the contents (decoded using the Character set supplied) of a file location as a single string. Also see read file lines enc.

function readBase64

str readBase64(loc file)
throws PathNotFound, IO

str readBase64(loc file)
throws PathNotFound, IO

function uuencode

str uuencode(loc file)

function writeBase64

void writeBase64(loc file, str content)
throws PathNotFound, IO

void writeBase64(loc file, str content)
throws PathNotFound, IO

function uudecode

void uudecode(loc file, str content)

function readFileBytes

list[int] readFileBytes(loc file)
throws PathNotFound, IO

list[int] readFileBytes(loc file)
throws PathNotFound, IO

Synopsis

Read the contents of a file and return it as a list of bytes.

function readFileLines

list[str] readFileLines(loc file, str charset=DEFAULT_CHARSET)
throws PathNotFound, IO

list[str] readFileLines(loc file, str charset=DEFAULT_CHARSET)
throws PathNotFound, IO

Synopsis

Read the contents of a file location and return it as a list of strings.

Description

Return the contents of a file location as a list of lines. Also see read file.

Encoding

Look at read file to understand how this function chooses the character set. If you know the character set used, please use read file lines enc.

Pitfalls

  • In case encoding is not known, we try to estimate as best as we can (see [readFile]).
  • We default to UTF-8, if the file was not encoded in UTF-8 but the first characters were valid UTF-8, you might get an decoding error or just strange looking characters (see read file).

function writeFileLines

void writeFileLines(loc file, list[str] lines, str charset=DEFAULT_CHARSET)

Synopsis

Writes a list of strings to a file, where each separate string is ended with a newline

Benefits

Pitfalls

  • if the individual elements of the list also contain newlines, the output may have more lines than list elements

function readFileLinesEnc

list[str] readFileLinesEnc(loc file, str charset)
throws PathNotFound, IO

list[str] readFileLinesEnc(loc file, str charset)
throws PathNotFound, IO

Synopsis

Read the contents of a file location and return it as a list of strings.

Description

Return the contents (decoded using the Character set supplied) of a file location as a list of lines. Also see read file lines.

function remove

void remove(loc file, bool recursive=true) throws IO

function writeFile

void writeFile(loc file, value V..., str charset=DEFAULT_CHARSET)
throws PathNotFound, IO

void writeFile(loc file, value V..., str charset=DEFAULT_CHARSET)
throws PathNotFound, IO

Synopsis

Write values to a file.

Description

Write a textual representation of some values to a file:

  • If a value is a simple string, the quotes are removed and the contents are de-escaped.
  • If a value has a non-terminal type, the parse tree is unparsed to produce a value.
  • All other values are printed as-is.
  • Each value is terminated by a newline character.

Files are encoded in UTF-8, in case this is not desired, use write file enc.

function writeFileBytes

void writeFileBytes(loc file, list[int] bytes)
throws PathNotFound, IO

void writeFileBytes(loc file, list[int] bytes)
throws PathNotFound, IO

Synopsis

Write a list of bytes to a file.

function writeFileEnc

void writeFileEnc(loc file, str charset, value V...) throws PathNotFound, IO

Synopsis

Write values to a file.

Description

Write a textual representation of some values to a file:

  • If a value is a simple string, the quotes are removed and the contents are de-escaped.
  • If a value has a non-terminal type, the parse tree is unparsed to produce a value.
  • All other values are printed as-is.
  • Each value is terminated by a newline character.

Files are encoded using the charset provided.

function md5HashFile

str md5HashFile(loc file)
throws PathNotFound, IO

str md5HashFile(loc file)
throws PathNotFound, IO

Synopsis

Read the contents of a location and return its MD5 hash.

Description

MD5 hash the contents of a file location.

function md5Hash

str md5Hash(value v)

str createLink(str title, str target)

function toBase64

str toBase64(loc file)
throws PathNotFound, IO

str toBase64(loc file)
throws PathNotFound, IO

function copy

void copy(loc source, loc target, bool recursive=false, bool overwrite=true) throws IO

function copyFile

void copyFile(loc source, loc target)

function copyDirectory

void copyDirectory(loc source, loc target)

function move

void move(loc source, loc target, bool overwrite=true) throws IO

function arbLoc

loc arbLoc()

data LocationChangeEvent

data LocationChangeEvent  
= changeEvent(loc src, LocationChangeType changeType, LocationType \type)
;

data LocationChangeType

data LocationChangeType  
= created()
| deleted()
| modified()
;

data LocationType

data LocationType  
= file()
| directory()
;

function watch

void watch(loc src, bool recursive, void (LocationChangeEvent event) watcher)

function unwatch

void unwatch(loc src, bool recursive, void (LocationChangeEvent event) watcher)