Considering a file with string on each lines, I want to create an array with each line of the file as an element of the array. I know I can do it like so:
import scala.io.Source
val path: String = "path/to/text/file.txt"
var array: Array[String] = new Array[String](0)
for (line <- Source.fromFile(path).getLines) {
array : = line
}
But it's quite long and maybe not very optimal. I look on the web and didn't find any better way of doing it. Do you have a better way of creating such array using Array built-in methods I may have missed or using map
or anything else ?
Thanks.
CodePudding user response:
Using getLines returns an Iteration, from which you can use toArray
val path: String = "path/to/text/file.txt"
val array: Array[String] = Source.fromFile(path).getLines.toArray
CodePudding user response:
On top of the answer by @TheFourthBird:
In your code you don't close the file. This might be ok for short programs, but in a long-lived process you should close it explicitly.
This can be accomplished by:
import scala.io.Source
import scala.util.{Try, Using}
val path: String = "path/to/text/file.txt"
val tryLines: Try[Array[String]] = Using(Source.fromFile(path))(_.getLines.toArray)