6

How would I go about counting the number of lines in a text file similar to wc -l on the unix command line in scala?

dave
  • 12,406
  • 10
  • 42
  • 59

3 Answers3

20
io.Source.fromFile("file.txt").getLines.size

Note that getLines returns an Iterator[String] so you aren't actually reading the whole file into memory.

Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
  • 2
    Similar to an answer to your [other question](http://stackoverflow.com/q/8865434/115478), this also leaks file descriptors. – leedm777 Jan 16 '12 at 05:30
4

Cribbing from another answer 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
  }
}
Community
  • 1
  • 1
leedm777
  • 23,444
  • 10
  • 58
  • 87
0
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) }
Jeremy D
  • 4,787
  • 1
  • 31
  • 38