[英]scala comma separated string to double-quoted comma separated string
I have a file which contains certain string like -我有一个包含某些字符串的文件,例如 -
Apple
Google
Microsoft
I am reading in this file as我在这个文件中阅读
val lines = scala.io.Source.fromFile(filePath).mkString.replace("\n", ",")
Which results in a comma separated list of string.这导致以逗号分隔的字符串列表。 However what I really want is
"Apple","Google","Microsoft"
然而我真正想要的是
"Apple","Google","Microsoft"
If I add double quotes in the string replace while reading in the file I while have to take care of the first and last double quotes which won't be ideal.如果我在读取文件时在字符串替换中添加双引号,我同时必须处理第一个和最后一个双引号,这并不理想。 How should I go about this?
我应该怎么做?
One option is to load each line into an Iterator
and then let mkString
apply the commas and quote marks.一种选择是将每一行加载到
Iterator
,然后让mkString
应用逗号和引号。
io.Source
.fromFile(filePath)
.getLines()
.mkString("\"","\",\"","\"")
//res0: String = "Apple","Google","Microsoft"
Similar to jwvh's answer but with Using
for resource management类似jwvh的答案,但与
Using
资源管理
import scala.util.Using
import scala.io.Source
Using.resource(Source.fromFile(filePath)) { file =>
file.getLines.map(line => s""""$line"""").mkString(",")
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.