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.

2
  • 1
    Source.fromFile(path).getLines.toArray Commented Dec 29, 2021 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 Commented Jan 6, 2022 at 8:28

2 Answers 2

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?

Sign up to request clarification or add additional context in comments.

Comments

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

4 Comments

Okay thanks ! I dunno no one is telling about it in tutorials etc. about arrays and file processing. ^^
@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 and look for your specific needs. 3. Because outside of toy examples, Source is a terrible way to process files.
@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.
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 ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.