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
Share:
10,521
macemers
Author by

macemers

Updated on June 28, 2022

Comments

  • macemers
    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
    Sergey Passichenko almost 10 years
    Actually, 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
    macemers almost 10 years
    Hi, where's the "additional memory" and "two traversal"? Would you please share a better solution?
  • 1esha
    1esha almost 10 years
    The question was about functional way, not about performance. Solution provides functional way, not imperative
  • 1esha
    1esha almost 10 years
    I have update answer for lower memory usage and one traversal
  • ziggystar
    ziggystar almost 10 years
    @SergeyPassichenko You know that getLines returns an Iterator[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
    Sergey Passichenko almost 10 years
    Sorry, I forgot about iterator :(
  • summerNight
    summerNight over 8 years
    So how do you save the changes made to a new file?