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
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
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.
You can replace with replaceAll with regular expression or
"a~ϕ~b~ϕ~c~ϕ~d~ϕ~e".filter(c => c.isLetter || c.isDigit).mkString(",")