欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Scala read file

程序员文章站 2022-04-19 17:17:00
...
// use loan pattern
// close resource after used
def using[A <: { def close(): Unit}, B]
      (resource: A)(f: A => B): B = {
  try {
    f(resource)
  } finally {
    resource.close()
  }
}

// use Option as return
def readTextFile(filename: String): Option[List[String]] = {
  try {
    val lines = using(Source.fromFile(filename)) {
      source =>
        source.getLines.toList
    }
    Some(lines)
  } catch {
    case e: Exception => None
  }
}

// print lines
val lines = readTextFile(filename).get
lines.foreach { line =>
  println(line)
}

转载于:https://www.jianshu.com/p/bc99e758654f