Number of lines in a file - Scala

How do I count the number of lines in a text file similar wc -lto the unix command line in scala?

+5
source share
3 answers
io.Source.fromFile("file.txt").getLines.size

Note that it getLinesreturns Iterator[String], so you are not actually reading the entire file in memory.

+17
source

Cribbing out another answer that I posted :

def lineCount(f: java.io.File): Int = {
  val src = io.Source.fromFile(f)
  try {
    src.getLines.size
  } finally {
    src.close()
  }
}

Or using scala-arm :

import resource._

def firstLine(f: java.io.File): Int = {
  managed(io.Source.fromFile(f)) acquireAndGet { src =>
    src.getLines.size
  }
}
+3
source
val source = Source.fromFile(new File("file")).getLines
var n = 1 ; while (source.hasNext) { printf("%d> %s", n, source.next) ; n += 1 }


val source = Source.fromFile(new File("file")).getLines
for ((line, n) <- source zipWithIndex) { printf("%d> %s", (n + 1), line) }
0
source

All Articles