我有一个如下所示的文本文件
a~ϕ~b~ϕ~c~ϕ~d~ϕ~e
1~ϕ~2~ϕ~3~ϕ~4~ϕ~5
我希望将以下输出写入文本文件
a,b,c,d,e
1,2,3,4,5
这是另一种方法,它使用临时文件替换~ϕ~分隔符来存储替换的中间结果:,
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))
}
}
请注意,这val outputLines = inputStream.getLines()将返回一个Iterator[String],这意味着我们懒惰地读取文件。这种方法允许我们格式化每一行并将其写回输出文件,避免将整个文件存储在内存中。
您可以用正则表达式替换 replaceAll 或
"a~ϕ~b~ϕ~c~ϕ~d~ϕ~e".filter(c => c.isLetter || c.isDigit).mkString(",")