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

时间:2017-03-03 21:46:40

标签: stream smalltalk

有没有办法在Smalltalk中逐行读取输入行? 我发现了一种方法,即使用“upTo:Character cr。” 还有其他方法吗? 或者我可以将该行读作字符串吗?

提前致谢。

1 个答案:

答案 0 :(得分:4)

以下是

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"
相关问题