如果您只想序列化单个列表或数组,而没有正确转义引号等:
scala> List(1,2,3,4).mkString(",")
res39: String = 1,2,3,4
如果您希望序列化稍微复杂的数据结构:
product-collections 将会将元组或者case类(任意Product)的集合序列化为csv,并且正确地转义引号。
scala> List ((1,"Jan"),
| (2,"Feb"),
| (3,"Mar","Extra column")).csvIterator.mkString("\n")
res41: String =
1,"Jan"
2,"Feb"
3,"Mar","Extra column"
product-collections 也可以直接写入 java.io.Writer
。它具有针对同类元组的集合 CollSeq
,不允许出现上述的“额外列”。
为了将您的原始数据转换为 product-collections 可处理的格式:
scala> CollSeq(scala.collection.mutable.ArrayBuffer("a","b","quoted \"stuff\""):_*)
res52: com.github.marklister.collections.immutable.CollSeq1[String] =
CollSeq((a),
(b),
(quoted "stuff"))
scala> res52.csvIterator.mkString("\n")
res53: String =
"a"
"b"
"quoted ""stuff"""