Smalltalk: Writing output to a file

浪子不回头ぞ 提交于 2019-12-07 04:49:49

问题


Usually with my output I am writing it to the Transcript with...

Transcript show:

How does one write the output to a file instead?


回答1:


You want to use a FileStream

See this link describing FileStreams

Excerpt below:


FileStream FileStreams support all of ExternalStreams protocol. They can be created to read, write, readWrite or append from/to a file. Creation:
* for reading:

      aStream := FileStream readonlyFileNamed:aFilenameString

* to read/write an existing file:

      aStream := FileStream oldFileNamed:aFilenameString

* to create a new file for writing:

      aStream := FileStream newFileNamed:aFilenameString

The above was the internal low level instance creation protocol, which is somewhat politically incorrect to use. For portability, please use the companion class Filename to create fileStreams:

* for reading:

      aStream := aFilenameString asFilename readStream

* to read/write an existing file:

      aStream := aFilenameString asFilename readWriteStream

* to create a new file for writing:

      aStream := aFilenameString asFilename writeStream

* to append to an existing file:

      aStream := aFilenameString asFilename appendingWriteStream



回答2:


| fileName aStream |

fileName := (Filename named: 'stream.st').

aStream := fileName readAppendStream.

aStream nextPutAll: 'What is the best class I have ever taken?'.

aStream cr.

aStream flush.

aStream nextPutAll: 'It is the VisualWorks Intro class!'.

aStream close.



回答3:


And then of course don't forget to handle the character encoding you want, if you're not writing binary or the default encoding. In Pharo/Squeak, set the converter to the needed TextConverter subclass.



来源:https://stackoverflow.com/questions/4055357/smalltalk-writing-output-to-a-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!