Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get first line from file in Scala

Tags:

parsing

csv

scala

I'd like to get just the first line from a CSV file in Scala, how would I go about doing that without using getLine(0) (it's deprecated)?

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

dave


2 Answers

If you don't care about releasing the file resource after using it, the following is a very convienient way:

Source.fromFile("myfile.csv").getLines.next()

like image 57
ziggystar Avatar answered Oct 11 '22 22:10

ziggystar


If you want to close the file, and you want to get an empty collection rather than throw an error if the file is actually empty, then

val myLine = {
  val src = Source.fromFile("myfile.csv")
  val line = src.getLines.take(1).toList
  src.close
  line
}

is about the shortest way you can do it if you restrict yourself to the standard library.

like image 26
Rex Kerr Avatar answered Oct 11 '22 23:10

Rex Kerr