2.3: Opening Read and Write Streams
- Page ID
- 43794
To open a stream on a file, just ask the reference for a read- or write-stream using the message writeStream
or readStream
as follows:
| working stream | working := FileSystem disk workingDirectory. stream := (working / 'foo.txt') writeStream. stream nextPutAll: 'Hello World'. stream close. stream := (working / 'foo.txt') readStream. stream contents. → 'Hello World' stream close.
Please note that writeStream
overrides any existing file and readStream
throws an exception if the file does not exist. Forgetting to close stream is a common mistake, for which even advanced programmers regularly fall into. Closing a stream frees low level resources, which is a good thing to do. The messages readStreamDo:
and writeStreamDo:
frees the programmer from explicitly closing the stream. Consider:
| working | working := FileSystem disk workingDirectory. working / 'foo.txt' writeStreamDo: [ :stream | stream nextPutAll: 'Hello World' ]. working / 'foo.txt' readStreamDo: [ :stream | stream contents ].
Keep in mind that file may be easily overridden without giving any warning. Consider the following situation:
| working | working := FileSystem disk workingDirectory. working / 'authors.txt' readStreamDo: [ :stream | stream contents ]. → 'stephane alexandre damien jannik'
The file authors.txt
may be simply overridden with:
FileSystem disk workingDirectory / 'authors.txt' writeStreamDo: [ :stream | stream nextPutAll: 'bob joe'].
Reading back the file may give an odd result:
| working | working := FileSystem disk workingDirectory. working / 'authors.txt' readStreamDo: [ :stream | stream contents ]. → 'bob joee alexandre damien jannik'
We can also use the message openFilestream: aString writable: aBoolean
to get a stream with the corresponding write status.
| stream | stream := FileSystem disk openFileStream: 'authors.txt' writable: true. stream nextPutAll: 'stephane alexandre damien jannik'.
Have a look at the streams protocol of FileReference
for other convenience methods.