简介
使用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}") }) } }
时间: 2024-10-11 22:05:56