Scala read file and split and modify each line
10,521
Solution 1
One traversal and no additional memory
Source
.fromFile("files/ChargeNames")
.getLines
.map { line =>
//do stuff with line like
line.replace('a', 'b')
}
.foreach(println)
Or code which is a little bit faster, according to @ziggystar
Source
.fromFile("files/ChargeNames")
.getLines
.foreach { line =>
//do stuff with line like
println(line.replace('a', 'b'))
}
Solution 2
val ans = for (line <- Source.fromFile.getLines) yield (line.replace('a', 'b')
ans foreach println
Author by
macemers
Updated on June 28, 2022Comments
-
macemers over 1 year
I'm new to Scala. I want to read lines from a text file and split and make changes to each lines and output them.
Here is what I got:
val pre:String = " <value enum=\"" val mid:String = "\" description=\"" val sur:String = "\"/>" for(line<-Source.fromFile("files/ChargeNames").getLines){ var array = line.split("\"") println(pre+array(1)+mid+array(3)+sur); }
It works but in a Object-Oriented programming way rather than a Functional programming way.
I want to get familiar with Scala so anyone who could change my codes in Functional programming way?
Thx.
-
Sergey Passichenko almost 10 yearsActually, this solution is not better than original. It requires additional memory and makes two traversal instead of one. And in "real world" you should close
Source
after using. -
macemers almost 10 yearsHi, where's the "additional memory" and "two traversal"? Would you please share a better solution?
-
1esha almost 10 yearsThe question was about functional way, not about performance. Solution provides functional way, not imperative
-
1esha almost 10 yearsI have update answer for lower memory usage and one traversal
-
ziggystar almost 10 years@SergeyPassichenko You know that
getLines
returns anIterator[String]
? There is one traversal in both cases. So the answer doesn't make much sense (the comment and the second code block). Though the second block is more performant for other reasons. -
Sergey Passichenko almost 10 yearsSorry, I forgot about iterator :(
-
summerNight over 8 yearsSo how do you save the changes made to a new file?