我正在尝试以块的形式读取输入流:
import scala.io.Source
// val in = Source.stdin.mkString("")
val in = Source.fromFile("/shared/american.txt").getLines.mkString("")
var ptr = 0
val out = Stream.continually {
val ix = math.min(ptr+80,in.length)
val ret = in.substring(ptr, ix)
ptr = ix
ret
}
out: scala.collection.immutable.Stream[String] = Stream(Unmentionable has an enthusiastic 35% of the popular vote. I discount the other 10% or s, ?)
但是块中take
的语法是什么?我试过了:
val chunks = out.takeWhile( ptr < in.length)
<console>:13: error: type mismatch;
found : Boolean
required: String => Boolean
val ret = out.takeWhile( ptr < in.length)
答案 0 :(得分:1)
以80个字符的块读取文件?怎么回事?
val in = io.Source.fromFile("file.txt").mkString.grouped(80)
while (in.hasNext) {
// in.next is your chunk
}
答案 1 :(得分:0)
你想要完成什么?如果您只是想将字符串(文件)分成块,则可以使用.grouped()
或.groupBy()
函数。
对于您当前的错误,编译器会告诉您需要执行的操作。你给了一个布尔:
val chunks = out.takeWhile(ptr < in.length) // ptr < in.length evaluates to a boolean
但你需要给一个带String的函数并返回一个布尔值:
val chunks = out.takeWhile(s => ptr < s.length) // Something like this