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

来源:互联网 发布:淘宝网运费险 编辑:程序博客网 时间:2024/06/05 09:24
使用scala的load pattern自动关闭打开的资源 读取properties文件

目录[-]

  • 简介
  • 依赖的jar
  • 示例代码
  • 简介

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

    读取properties文件

    依赖的jar

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

    ?
    1
    2
    3
    4
    5
    <dependency>
        <groupId>com.jsuereth</groupId>
        <artifactId>scala-arm_${scala.binary.version}</artifactId>
        <version>1.4</version>
    </dependency>

    示例代码

    ?
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    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: => 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}")
        })
      }
    }

    0 0
    原创粉丝点击