Pacific-Design.com

    
Home Index

1. Scala

2. Files IO

+ Multiple Files

Scala / Files IO /

Read and parse comma delimited file


object FileParser extends App {
  println("Month, Income, Expenses, Profit")
  val bufferedSource = io.Source.fromFile("/tmp/flatfile.dat")

  for (line <- bufferedSource.getLines) {
    val cols = line.split(",").map(_.trim)
    println(s"${cols(0)}|${cols(1)}|${cols(2)}|${cols(3)}")
  }

  bufferedSource.close
}

Named Variables


object FileParser extends App {
  println("Month, Income, Expenses, Profit")
  val bufferedSource = io.Source.fromFile("/tmp/flatfile.dat")

  for (line <- bufferedSource.getLines) {
    val Array(month, revenue, expenses, profit) = line.split(",").map(_.trim)
    println(s"$month $revenue $expenses $profit")
  }

  bufferedSource.close
}

/tmp/flatfile.dat


January, 10000.00, 9000.00, 1000.00
February, 11000.00, 9500.00, 1500.00
March, 12000.00, 10000.00, 2000.00