views:

90

answers:

1

What's the best way to do file IO in Scala 2.8?

All I want to do is cut a massive CSV file into lots of smaller ones with, say 1000 lines of data per file, and each file retaining the header.

+9  A: 

For simple tasks like this I would use scala.io.Source. An example would look like this:

val input = io.Source.fromFile("input.csv").getLines()

if (input.hasNext) {
  // assuming one header line
  val header = List(input.next())

  for ((i, lines) <- Iterator.from(1) zip input.grouped(linesPerFile)) {
    val out = createWriter(i) // Create a file for index i
    (header.iterator ++ lines.iterator).foreach(out.println)
    out.close
  }
}
Moritz
Great. Forced me to learn what 'zip' does too!
Pengin