David Contreras
David Contreras

Reputation: 13

How to turn a disorganized text file into an Array[String] in Scala?

I have a text file that looks like this:

 10 10 
 54 129 155 559 10.00 10.00 
 99999 3 15 15 15 15 15 15 
 15 15 
 120 195 258 744 10.00 10.00 
 3 99999 15 15 15 15 15 15 
 15 15 

amount of ints/doubles per line can vary.

I can't read line by line because the amount on them are not constant. I've been trying with split, mkString and such to no success.

val lines = Source.fromFile(s"/tmp/$filepath")
                  .getLines.mkString
                  .split("\n").mkString
                  .split(" ").map(_.trim)

When I try to read it like:

lines(0).toInt

It return: [NumberFormatException: For input string: ""]

Need that to look like this:

A = Array('10', '10', '54', '129', '155', '559', '10.00', '10.00', '99999', '3', '15', '15', '15', '15', '15', '15', '15', '15', '120', '195', '258', '744', '10.00', '10.00', '3', '99999', '15', '15', '15', '15', '15', '15', '15', '15')

Upvotes: 0

Views: 30

Answers (1)

Andrey Tyukin
Andrey Tyukin

Reputation: 44918

Not sure what you wanted with all those mkStrings there... Anyway, this here works just fine:

io.Source.fromFile("input.txt").getLines.flatMap(_.trim.split(" +")).toArray

Upvotes: 3

Related Questions