在 Smalltalk 中逐行读取输入流中的数据

Read a data from an input Stream line by line in Smalltalk

有没有办法在 Smalltalk 中逐行读取输入行? 我找到了一种方法,就是使用 "upTo: Character cr." 还有其他方法吗? 或者我可以将该行作为字符串读取吗?

提前致谢。

方法如下

string := 'line one
line two
line three'.
stream := string readStream

现在,

stream nextLine "answers with 'line one'".
stream nextLine "answers with 'line two'".
stream nextLine "answers with 'line three'"

此时

stream atEnd "answers with true"

请注意,nextLine 使用了行尾,但没有将其包含在答案中。如果最后一行没有行尾,那么 nextLine 将在最后停止。

另请注意,这允许在 stream 有更多数据时循环读取行

[stream atEnd] whileFalse: [self doSomethingWith: stream nextLine]

如果你想从头再读一遍:

stream reset

如果您想回到之前的位置:

stream position: pos

例如

stream nextLine "read first line".
pos2 := stream position "position of the second line".
stream nextLine "read second line".
stream nextLine "read third line".
stream position: pos2 "get back to line 2".
stream nextLine "again, line 2"