我有一个文本文件如下所示
a~ϕ~b~ϕ~c~ϕ~d~ϕ~e
1~ϕ~2~ϕ~3~ϕ~4~ϕ~5我希望将下面的输出写入文本文件
a,b,c,d,e
1,2,3,4,5发布于 2019-11-29 12:55:37
下面是另一种方法,它使用临时文件来存储替换的中间结果,将~ϕ~分隔器替换为,:
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],这意味着我们延迟读取文件。这种方法允许我们格式化每一行并将其写回输出文件,避免将整个文件存储在内存中。
发布于 2019-11-29 08:05:45
可以用replaceAll替换为正则表达式或
“a~.filter~b~b~ϕ~c~c~ϕ~d~ϕ~e”.mkString(c => c.isLetter连体c.isDigit).mkString(",")
https://stackoverflow.com/questions/59100209
复制相似问题