Peter Uhnak
Peter Uhnak

Reputation: 10217

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?

Upvotes: 3

Views: 389

Answers (3)

philippeback
philippeback

Reputation: 801

(FileSystem memory root / 'foo.txt')
  writeStreamDo: [ :out |
    out binary.
    (ZnCharacterWriteStream on: out encoding: #utf8) << '彼得' ].

should work.

Upvotes: 1

Leandro Caniglia
Leandro Caniglia

Reputation: 14868

Here is an expression that will do what you are looking for:

string := '彼得'.
file writeStreamDo: [:stream |
  #utf8 asZnCharacterEncoder
    next: string size
    putAll: string
    startingAt: 1
    toStream: stream]

Upvotes: 1

Alistair
Alistair

Reputation: 106

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.

Upvotes: 3

Related Questions