|
Hi,
here is a working example on how to use pipes. Feel free to comment,
question... Thank you for reading.
| readFileStream inputStream copyStream outputStream |
"Writes some random numbers to a text file. Opening this file with an
editor will show exactly this string. The file size is equivalent to
the size of the string (61 bytes)."
NSWriteFileTextStream
fileNamed: 'testScenario1.txt' do: [:stream | stream nextPutAll: '83
117 99 99 101 115 115 32 119 105 116 104 32 78 105 108 101'].
"Opens the previous file for reading"
readFileStream := NSReadFileTextStream fileNamed: 'testScenario1.txt'.
"Reads the file and interprets the characters as space-separated numbers"
inputStream := NSNumberReader inputStream: readFileStream.
"Creates a new stream to read from and write to a new array"
copyStream := NSReadWriteCollectionStream on: Array new.
"Creates a T as with the unix tee command. Everything that goes in
the pipe will be copied to the copyStream"
inputStream := NSTee inputStream: inputStream outputStream: copyStream.
"Writes each number in the pipe to a byte in a new file. The file
size will be equivalent to the number of numbers in the input stream
(17 bytes)"
outputStream := NSWriteFileBinaryStream fileNamed: 'testScenario1.bin'.
"Writes everything that is in the inputStream to the outputStream.
This does not consume squeak memory because the characters are read
one after the other and written immediatly to the outputStream"
NSDrainer drainWithLowMemoryFrom: inputStream to: outputStream.
"Closes the 2 open files"
readFileStream close.
outputStream close.
"Verifies the copyStream contains the numbers"
self assert: copyStream contents = #( 83 117 99 99 101 115 115 32
119 105 116 104 32 78 105 108 101).
"Opens the binary file as if it were textual, i.e. reads all the
numbers as if they were ascii values of characters"
NSReadFileTextStream
fileNamed: 'testScenario1.bin'
do: [:stream |
"It seems the random numbers meant something after all"
self assert: stream upToEnd = 'Success with Nile']
What do you think about this example?
--
Damien Cassou
|