Scala-具有行号识别功能的ReadLines

时间:2019-03-11 16:53:45

标签: scala file-io

我正在尝试从Scala中的(\ n分隔)文件中读取。我想将文件的最后一行和倒数第二行与其他行区别对待。我该如何实现?据我所知,LineNumberedReaderBufferedReader可以获取当前行号,但不知道行总数(以不同方式处理最后一行)。期望的:

var aLine = lineNumberedReader.readLine
while (aLine != null) {
   val currentLineNum: Int = lineNumberedReader.getLineNumber
   if (currentLineNum == total_line_count - 1) {
       do_this // To know if its the last line/ second to last, I need the total_line_count available in hand. which I (maybe incorrectly?) believe needs a file iteration by itself
   } else {
       do_that
   }
   aLine = lineNumberedReader.readLine
}

Scala io.Source存在相同的问题。它至少需要两次文件迭代。任何想法/ API都可以通过一次迭代来实现?

编辑:扩展问题以包括倒数第二行的情况

1 个答案:

答案 0 :(得分:2)

也许是这样?

val lines = Source
  .fromFile("filename")
  .getLines
lines.foreach { line => 
   if (lines.hasNext) doThis(line) else doThat(line)
}

对于前者,它会涉及更多:

val it = Source.fromFile("filename").getLines.sliding(2)
it.foreach { 
 case x :: _ if it.hasNext => doCommon(x) 
 case x :: y :: _ => doBeforeLast(x); doLast(y)
}

或者通常是N-before-last(在您再次编辑问题之前:D):

val it = Source.fromFile("filename").getLines.sliding(n+1)
it.foreach {
  case x :: _ if it.hasNext => doCommon(x)
  case tail => doNBeforeLast(tail)
}