How to work with the file system
Glamorous Toolkit, like any Smalltalk system, is built around an image. That does not mean it can't communicate with the outside world, like the file system. On the contrary. The file system is nicely modelled inside the image. For example, inspect this:
'.' asFileReference
This page described basic operations for working with files and directories.
Basic model
The class FileReference
provides the main high-level API for working with files and folders. It holds a Path
and a FileSystem
and can manipulate File
objects, which provide the basic set of operations for working files on disk.
A Path
abstracts locations on the file system, and can be relative or absolute. FileSystem
defind protocol for interacting with filesystems. It hold a reference to
a concrete store (a subinstance of FileSystemStore
) where files are saved; this can be on disk (DiskStore
) or in memory (MemoryStore
).
Writing to a text file
The method AbstractFileReference>>#writeStreamDo:
writes to a file using a utf8-encoded buffered character stream. It gets the stream as a parameter, and makes sure the stream gets closed after writting is done.
textFile := './example.txt' asFileReference. textFile writeStreamDo: [ :aStream | aStream nextPutAll: 'Content in a text file' ]. textFile
Reading from a text file
The method AbstractFileReference>>#readStreamDo:
reads the content of a text file using a utf8-encoded buffered character stream.
textFile := './example.txt' asFileReference. contents := nil. textFile readStreamDo: [ :aStream | contents := aStream contents ]. contents
A stream allows us to read the content in chunks. In case we are simply interested in the entire content we can use AbstractFileReference>>#contents
.
textFile := './example.txt' asFileReference. contents := textFile contents