Write a long String with a Stream
Jump to navigation
Jump to search
TODO. Redo the example without using structures the reader does not have.
Problem. You need to compose a long block of text, what you usually do in scripting languages is appending a String to another until you get what you need. You can do it also in Smalltalk but it is not recommended in books.
Solution. Adapted from "Smalltalk by Example(1997)". You must guess approximately the size of the string you want to build, then open a write stream on it and add stuff. The better you guess the better the program will run, that is faster and without wasting memory. This code writes down a list of items as a CSV string that then you may write on disk.
st _ (String new: 10000) writeStream.
st nextPutAll: ('name, code, weight \n' printf: #()).
itemsList do: [ :item |
st nextPutAll: item name; nextPutAll: ', '.
st nextPutAll: item code; nextPutAll: ', '.
st nextPutAll: art weight asString; nextPut: Character newLineCharacter .
].
outString _ st contents.