OpenCSV を利用します。
<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>3.7</version>
</dependency>
libraryDependencies += "com.opencsv" % "opencsv" % "3.7"
sample.csv
1,2,3
4,5,6
Main.scala
import com.opencsv.CSVReader
import scala.util.control.Breaks._
import java.io.FileReader
object Main {
def main(args: Array[String]): Unit = {
val reader = new CSVReader(new FileReader("sample.csv"))
breakable {
while(true) {
val line = reader.readNext
if (line == null) {
break
}
for(col <- line) { // Array[String]
print(' ' + col)
}
println
}
}
}
}
val reader = new CSVReader(new FileReader("sample.tsv"), '\t')
インポート文の変更
import java.io.FileReader
↓
import java.io.{FileInputStream, InputStreamReader}
Reader の差し替え
val reader = new CSVReader(new FileReader("sample.csv"))
↓
val fis = new FileInputStream("sample.csv")
val isr = new InputStreamReader(fis, "Shift_JIS")
val reader = new CSVReader(isr)
import com.opencsv.CSVWriter
import java.io.FileWriter
object Main {
def main(args: Array[String]): Unit = {
val writer = new CSVWriter(new FileWriter("output.csv"))
val strArr = Array("a", "b", "c")
writer.writeNext(strArr)
writer.flush // これがないと出力されないことがあります。
}
}
val writer = new CSVWriter(new FileWriter("output.tsv"), '\t')
インポート文の変更
import java.io.FileWriter
↓
import java.io.{FileOutputStream, OutputStreamWriter}
Writer の差し替え
val writer = new CSVWriter(new FileWriter("output.csv"))
↓
val fos = new FileOutputStream("output.csv")
val osw = new OutputStreamWriter(fos, "Shift_JIS")
val writer = new CSVWriter(osw)