Search code examples
scalafilewritefile

How to add an element at the beginning of a line in a file in Scala


I have a file, e.g., like this:

// file_1.txt
10 2 3
20 5 6
30 8 9

I need to write a letter with a space before each line that meets a criterion regarding the first value / number in the line, e.g., if I give the value 20 then the file should look like this:

// file_1.txt
10 2 3
c 20 5 6
30 8 9

How I can achieve this in Scala?

This is what I am trying, till now:

import java.io._
import scala.io.Source

object Example_01_IO {

  val s = Source.fromFile("example_01_txt")

  val source = s.getLines()
  val destination = new PrintWriter(new File("des_example_01.txt"))
  val toComment = Array(-10, 20, -30)

  def main(args: Array[String]): Unit = {


    for (line <- source) {
      //if(line_begins_with_any_value_from_toComments_then_write_a_"c"_infront_of_that_line){
        println(line)
        destination.write("c" + line)
        destination.write("\n")
      //}

    }

    s.close()
    destination.close()

  }
}

I can write into another file, let's say, but I need to write in the same file, and only when a line meets a such condition.

I would appreciate any help.


Solution

  • Starting from what you have, all you really need to add is a way to check whether the current line starts with a number that is in your Array.

    One way to do that is split the line on every space so you get a list of all the numbers on that line. Then take only the first of that list and convert it to an Int. Then you can simply check whether that Int is present in your Array of allowed numbers.

    import java.io._
    import scala.io.Source
    
    object Example_01_IO {
    
      val s = Source.fromFile("example_01_txt")
    
      val source = s.getLines()
      val destination = new PrintWriter(new File("des_example_01.txt"))
      val toComment = Array(-10, 20, -30)
    
      def main(args: Array[String]): Unit = {
        def startsWithOneOf(line: String, list: Array[Int]) = 
          list.contains(line.split(" ").head.toInt)
    
        for (line <- source) {
          val lineOut = if (startsWithOneOf(line, toComment)) s"c $line" else line
          destination.write(lineOut)
          destination.write("\n")
        }
    
        s.close()
        destination.close()
    
      }
    }