Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

count number of lines in file - Scala

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?

like image 901
dave Avatar asked Jan 14 '12 21:01

dave


2 Answers

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.

like image 191
Tomasz Nurkiewicz Avatar answered Sep 28 '22 03:09

Tomasz Nurkiewicz


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
  }
}
like image 24
leedm777 Avatar answered Sep 28 '22 05:09

leedm777