Pravinkumar Hadpad
Pravinkumar Hadpad

Reputation: 109

How to read line with comma-separated fields from file?

I have task to read a positional file. I am able to read positional file with hard-coded data length in code but my task is to read data lengths from external file.

val lengths = Seq(3,10,5,4) // <-- I'd like to read it from an external file

Upvotes: 0

Views: 525

Answers (1)

Jacek Laskowski
Jacek Laskowski

Reputation: 74709

Say, you have a file with the following content (that corresponds to the positions):

$ cat positions.csv
3,10,5,4

In Scala, you could read the file as follows:

val lengths = scala.io.Source.
  fromFile("positions.csv").
  getLines.
  take(1).
  toArray.
  head.
  split(",").
  map(_.toInt).
  toSeq
scala> lengths.foreach(println)
3
10
5
4

Upvotes: 1

Related Questions