Slate Living Tutorial

to those about to rock...

Files

Slate has a File module for manipulating files.

Opening a file and reading data

inFile: (File newNamed:'/path/to/file' &mode: File Read).

The above opens a new file for reading and assigns it to a predefined slot named inFile.

To do anything with a File object's stream, we use the sessionDo method - this takes care of opening and closing the file.

inFile sessionDo:
[| :in stream |
    stream: in reader.
    [stream isAtEnd] whileFalse: [inform: (stream nextLine)].
].

The above snippet reads data from inFile a line at a time and prints it using the inform message. The :in symbol references inFile and the stream slot is assigned the to the file's reader stream.

We can also do the following to achieve the same result as the previous example:

inFile reader sessionDo: 
[| :in | 
    in lines do: 
    [| :line | 
        inform: line ]].

The lines method will return a sequence of lines in the file and we can call sessionDo directly on the reader stream.

Writing data to a file

To write to an existing file, use Write or ReadWrite modes, to write to a new file use CreateWrite. Note, CreateWrite will overwrite an existing file.

outFile: (File newNamed:'/path/to/file' &mode: File CreateWrite).

outFile writer sessionDo:
[| :out |
    out nextPutAll: 'This is some output\n'].

This code is self-explanatory, the nextPutAll method writes out its argument to the stream.

out ; 'This ' ; 'is some' ; 'output\n'.

The ; selector can also be used, it allows sending multiple sequences to a stream at one time (similar to << in C++).