2-scala文件操作--自动关闭打开的资源,读取properties文件

简介

使用scala的loan pattern自动关闭打开的资源

读取properties文件

依赖的jar

使用scala_arm库自动关闭资源文件时,需要引入以下依赖:

<dependency>
			<groupId>com.jsuereth</groupId>
			<artifactId>scala-arm_${scala.binary.version}</artifactId>
			<version>1.4</version>
		</dependency>

示例代码

import java.io.InputStream
import java.util.Properties

import scala.collection.JavaConversions.propertiesAsScalaMap

import resource.managed
import test.Control._

object Control {
  def using[A <: { def close(): Unit }, B](resource: A)(f: A => B): B =
    try {
      f(resource)
    } finally {
      if (resource != null)
        resource.close()
    }
}

object FileOperator extends App {
  val prop = new Properties()
  //读取classpath下的配置文件
  //读取properties文件
  //使用scala_arm自动关闭打开的文件资源
  for (
    source <- managed(FileOperator.getClass.getClassLoader.getResourceAsStream("db.properties"))
  ) {
    printProp(source)
  }

  //使用using自动关闭打开的文件资源
  using(FileOperator.getClass.getClassLoader.getResourceAsStream("db.properties")) { source =>
    {
      printProp(source)
    }
  }
  //使用绝对路径读取文件
  val res = readTextFile("D:/scalawork/scala-learn/src/main/resources/db.properties")
  res match {
    case Some(lines) => lines.foreach(println)
    case None        => println("couldn't read file")
  }

  //处理异常,返回Option
  def readTextFile(filename: String): Option[List[String]] = {
    try {
      val lines = using(io.Source.fromFile(filename)) { source =>
        (for (line <- source.getLines) yield line).toList
      }
      Some(lines)
    } catch {
      case e: Exception => None
    }
  }

  //加载properties并转换为HashMap,读取其内容
  def printProp(source: InputStream) = {
    prop.load(source)
    println(prop.getProperty("jdbc.idleMaxAge"))
    prop.foreach(ele => {
      println(s"${ele._1} => ${ele._2}")
    })
  }
}


转载于:https://my.oschina.net/cloudcoder/blog/491163

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值