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)?
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()
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.
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