我正在使用play framework Iteratee来读取文件。我想按块处理这个文件块(对于每一步)。如何使用Play Iteratees按块读取和处理文件块(对于块的每个步骤)
我撰写下列步骤:
groupByLines: Enumeratee[Array[Byte], List[String]]
turnIntoLines: Enumeratee[List[String], List[Line]]
(I定义case class Line(number: Int, value: String)
)parseChunk: Iteratee[List[Line], Try[List[T]]]
(例如CSV解析)
要定义groupByLines
,我需要使用Iteratee.fold
将前一个块的最后一行与当前块的第一个连接起来。
问题是,这会创建一个包含文件所有行的单个块。
但我想按块处理文件块。我的意思是groupByLines
应该产生200行(例如)的块。
同样的问题发生在turnIntoLine
。我也使用fold
来创建线。我需要使用累加器(由fold
提供)来压缩行号和行内容。
我是一个玩游戏iteratee的初学者。
这里是我的代码:
val chunkSize = 1024 * 8
val enumerator: Enumerator[Array[Byte]] = Enumerator.fromFile(file, chunkSize)
def isLastChunk(chunk: Array[Byte]): Boolean = {
chunk.length < chunkSize
}
val groupByLines: Enumeratee[Array[Byte], List[String]] = Enumeratee.grouped {
println("groupByLines")
Iteratee.fold[Array[Byte], (String, List[String])]("", List.empty) {
case ((accLast, accLines), chunk) =>
println("groupByLines chunk size " + chunk.length)
new String(chunk)
.trim
.split("\n")
.toList match {
case lines @ Cons(h, tail) =>
val lineBetween2Chunks: String = accLast + h
val goodLines =
isLastChunk(chunk) match {
case true => Cons(lineBetween2Chunks, tail)
case false => Cons(lineBetween2Chunks, tail).init
}
(lines.last, accLines ++ goodLines)
case Nil => ("", accLines)
}
}.map(_._2)
}
val turnIntoLines: Enumeratee[List[String], List[Line]] = Enumeratee.grouped {
println("turnIntoLines")
Iteratee.fold[List[String], (Int, List[Line])](0, List.empty) {
case ((index, accLines), chunk) =>
println("turnIntoLines chunk size " + chunk.length)
val lines =
((Stream from index) zip chunk).map {
case (lineNumber, content) => Line(lineNumber, content)
}.toList
(index + chunk.length, lines ++ accLines)
}.map(_._2)
}