1

I have a text file looks like below

a~ϕ~b~ϕ~c~ϕ~d~ϕ~e

1~ϕ~2~ϕ~3~ϕ~4~ϕ~5

I want the the below output to be written into the text file

a,b,c,d,e

1,2,3,4,5
jwvh
  • 50,871
  • 7
  • 38
  • 64
Nilay
  • 113
  • 7
  • 1
    As for basic file IO, have you seen [this](https://stackoverflow.com/questions/1284423/read-entire-file-in-scala), [this](https://stackoverflow.com/questions/4604237/how-to-write-to-a-file-in-scala), or [this](https://stackoverflow.com/questions/6879427/scala-write-string-to-file-in-one-statement)? – jwvh Nov 29 '19 at 09:09
  • 2
    You need help with? The replacement? The file handling? Correctness of the code? Performance of the code? - What have you tried? What problems for you have? Are you new to Scala or programming in general? - This is just for practicing basic IO stuff, or this is a real problem you have at work? - All that questions will help us to provide a better answer to your problem. – Luis Miguel Mejía Suárez Nov 29 '19 at 11:51

2 Answers2

2

Here is a another approach which replaces ~ϕ~ seperator with , using a temporary file to store the intermediate results of replacement:

import java.io.{File, PrintStream}
import scala.io.{Codec, Source}

object ReplaceIOStringExample {
  val Sep = "~ϕ~"

  def main(args: Array[String]): Unit = {
    replaceFile("/tmp/test.data")
  }

  def replaceFile(path: String) : Unit = {
    val inputStream = Source.fromFile(path)(Codec.UTF8)

    val outputLines = inputStream.getLines()

    new PrintStream(path + ".bak") {
      outputLines.foreach { line =>
        val formatted = line.split(Sep).mkString(",") + "\n"
        write(formatted.getBytes("UTF8"))
      }
    }

    //delete old file
    new File(path).delete()

    //rename .bak file to the initial file name
    new File(path + ".bak").renameTo(new File(path))
  }
}

Notice that val outputLines = inputStream.getLines() will return an Iterator[String] which means that we read the file lazily. This approach allows us to format each line and write it back to the output file avoiding storing the whole file in the memory.

abiratsis
  • 7,051
  • 3
  • 28
  • 46
0

You can replace with replaceAll with regular expression or

"a~ϕ~b~ϕ~c~ϕ~d~ϕ~e".filter(c => c.isLetter || c.isDigit).mkString(",")

  • This is justa small data in a file..I want something like reading a file and then replace it – Nilay Nov 29 '19 at 08:14