Search code examples
unicodesmalltalkmemorystreampharo

Writing unicode/utf-8 data to a memory file


How can one write unicode/utf-8 to a file in MemoryStore?

Normally I can just do the following

fs := FileSystem workingDirectory.
file := fs / 'file.txt'.
file writeStreamDo: [ :stream | stream << '彼得' ].
file contents. "'彼得'"

the stream there is a MultiByteFileStream.

However when I try to do the same on memory storage, I and up with an error

fs := FileSystem memory.
file := fs / 'file.txt'.
file writeStreamDo: [ :stream | stream << '彼得' ].

Error: Improper store into indexable object

Because stream there is an ordinary WriteStream.

I've tried to work around it by directly instantiating MultiByteFileStream, however that seems to require real file.

Is there another way?


Solution

  • It looks like the memory file system doesn't handle multibyte files by default. Try:

    | fs file stream |
    
    fs := FileSystem memory.
    file := fs / 'file.txt'.
    stream := MultiByteBinaryOrTextStream on: (fs open: file writable: true).
    stream converter: UTF8TextConverter new.
    [ stream << '彼得' ] ensure: [ stream close ].
    file.