Brief introduction
Automatically close open resources using Scala's loan pattern
Read the Properties file
Dependent jar
When you use the Scala_arm library to automatically close resource files, you need to introduce the following dependencies:
<dependency><groupid>com.jsuereth</groupid><artifactid>scala-arm_${ Scala.binary.version}</artifactid><version>1.4</version></dependency>
Sample code
import java.io.inputstreamimport java.util.propertiesimport Scala.collection.javaconversions.propertiesasscalamapimport resource.managedimport test. Control._object control { def using[a <: { def close (): UNIT&NBSP;},&NBSP;B] (resource: a) (f: a => b): b = try { f (Resource) } finally { if (resource != null) resource.close () }}object FileOperator extends App { val prop = new properties () //read the configuration file under Classpath // Read the properties file //use Scala_arm to automatically close open File Resources for ( source <- managed (FileOperator.getClass.getClassLoader.getResourceAsStream ("Db.prOperties ")) ) { printprop (source) } // Use the using to automatically close Open file resource using (FileOperator.getClass.getClassLoader.getResourceAsStream ("Db.properties")) { source => { printprop (source) } } //using an absolute path to read files 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 ") } //handles the exception and returns 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 } } // Load properties and convert to HashMap, read its contents def printprop (Source: inputstream) = { prop.load (source) println (Prop.getproperty ("Jdbc.idlemaxage")) prop.foreach (Ele => { println (S "${ele._1} => ${ele._2} ") }) }}
2-scala file operation--automatically closes open resources, reads properties file