Я использую Play Framework Iteratee для чтения файла. Я хотел бы обработать этот файл по частям (для каждого шага).
Я составляю следующие шаги:
groupByLines: Enumeratee[Array[Byte], List[String]]
turnIntoLines: Enumeratee[List[String], List[Line]]
(я определил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)
}