[英]In Pharo/Smalltalk: How to read a file with a specific encoding?
我目前正在閱讀這樣的文件:
dir := FileSystem disk workingDirectory.
stream := (dir / 'test.txt' ) readStream.
line := stream nextLine.
當文件是utf-8
編碼時,這可以工作,但是當文件有另一個編碼時我無法找到該做什么。
類ZnCharacterReadStream
和ZnCharacterWriteStream
提供了使用除UTF-8
編碼字符流的功能(這是默認設置)。 首先,需要將文件流轉換為binary
流。 在此之后,它可以被ZnCharacter*Stream
包裹。 以下是編寫和讀取文件的完整示例:
dir := FileSystem disk workingDirectory.
(dir / 'test.txt') writeStreamDo: [ :out |
encoded := ZnCharacterWriteStream on: (out binary) encoding: 'cp1252'.
encoded nextPutAll: 'Über?'.
].
content := '?'.
(dir / 'test.txt') readStreamDo: [ :in |
decoded := ZnCharacterReadStream on: (in binary) encoding: 'cp1252'.
content := decoded nextLine.
].
content. " -> should evaluate to 'Über?'"
有關詳細信息,請參閱Enterprise Pharo a Web Perspective一書,其中有一章介紹字符編碼。
對於Pharo 7,有這個文件流指南 ,建議:
('test.txt' asFileReference)
readStreamEncoded: 'cp-1250' do: [ :stream |
stream upToEnd ].
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.