How to get the first line from a file in Scala

I want to get only the first line from a CSV file in Scala, how would I do this without using getLine (0) (is it deprecated)?

+3
source share
4 answers

FWIW, here is what I will do (sticking to the standard library):

def firstLine(f: java.io.File): Option[String] = {
  val src = io.Source.fromFile(f)
  try {
    src.getLines.find(_ => true)
  } finally {
    src.close()
  }
}

Notes:

  • The function returns Option[String]instead List[String], since it always returns one or nothing. This is a more idiomatic Scala.
  • src closed correctly even if you cannot open the file, but reading throws an exception
  • Using .find(_ => true)to get the first element Iteratordoes not make me feel great, but there is no method nextOption, and this is better than converting to an intermediate Listone that you are not using.
  • IOException .

scala-arm, API , .

import resource._

def firstLine(f: java.io.File): Option[String] = {
  managed(io.Source.fromFile(f)) acquireAndGet { src =>
    src.getLines.find(_ => true)
  }
}
+8

, :

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

+10

, , ,

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

- , , .

+8

, , . , , :

val firstLine = {
  val inputFile = Source.fromFile(inputPath)
  val line = inputFile.bufferedReader.readLine
  inputFile.close
  line
}

1 Scala, , .

0

All Articles