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?
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.
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With