0

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.

Karzyfox
  • 319
  • 1
  • 2
  • 15
  • 1
    `Source.fromFile(path).getLines.toArray` – sarveshseri Dec 29 '21 at 16:14
  • @sarveshseri Thanks but this only loads the first 4080 lines while I need to load about 10,000 lines of data. I don't know if this is supposed to be a standard behavior but it's quite limiting – Karzyfox Jan 06 '22 at 08:28

2 Answers2

3

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)

See What's the right way to use scala.io.Source?

Lesiak
  • 22,088
  • 2
  • 41
  • 65
2

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
The fourth bird
  • 154,723
  • 16
  • 55
  • 70
  • 1
    Okay thanks ! I dunno no one is telling about it in tutorials etc. about arrays and file processing. ^^ – Karzyfox Dec 29 '21 at 11:04
  • @Karzyfox Probably because nobody should use `Array` in **Scala**, use `List` or any other real collection. 2. Because most people assume you would be able to just open the [**Scaladoc**](https://www.scala-lang.org/api/current/) and look for your specific needs. 3. Because outside of toy examples, `Source` is a terrible way to process files. – Luis Miguel Mejía Suárez Dec 29 '21 at 13:28
  • @Karzyfox Probably because there are thousands of different libraries which have millions of functions. Learning resources are supposed to give you the fundamental understanding. After that you can just look at the API docs and source code. – sarveshseri Dec 29 '21 at 16:16
  • I'm having issues with this solution : it only loads the first 4080 lines but ignore all other ones. Is it a normal behavior or an issue with my environnement ? – Karzyfox Jan 06 '22 at 08:26