Pra*_*rad 97 scala scala-collections
我有一个像下面的文件夹结构:
- main
-- java
-- resources
-- scalaresources
--- commandFiles
Run Code Online (Sandbox Code Playgroud)
在那个文件夹中,我有我必须阅读的文件.这是代码:
def readData(runtype: String, snmphost: String, comstring: String, specificType: String): Unit = {
val realOrInvFile = "/commandFiles/snmpcmds." +runtype.trim // these files are under commandFiles folder, which I have to read.
try {
if (specificType.equalsIgnoreCase("Cisco")) {
val specificDeviceFile: String = "/commandFiles/snmpcmds."+runtype.trim+ ".cisco"
val realOrInvCmdsList = scala.io.Source.fromFile(realOrInvFile).getLines().toList.filterNot(line => line.startsWith("#")).map{
//some code
}
val specificCmdsList = scala.io.Source.fromFile(specificDeviceFile).getLines().toList.filterNot(line => line.startsWith("#")).map{
//some code
}
}
} catch {
case e: Exception => e.printStackTrace
}
}
}
Run Code Online (Sandbox Code Playgroud)
And*_*ann 184
Scala中的资源与Java中的资源完全相同.最好遵循Java最佳实践并将所有资源放入src/main/resources和中src/test/resources.
示例文件夹结构:
testing_styles/
??? build.sbt
??? src
? ??? main
? ??? resources
? ? ??? readme.txt
Run Code Online (Sandbox Code Playgroud)
为了读取资源,对象Source提供了fromResource方法.
import scala.io.Source
val readmeText : Iterator[String] = Source.fromResource("readme.txt").getLines
Run Code Online (Sandbox Code Playgroud)
要读取资源,可以使用getClass.getResource和getClass.getResourceAsStream.
val stream: InputStream = getClass.getResourceAsStream("/readme.txt")
val lines: Iterator[String] = scala.io.Source.fromInputStream( stream ).getLines
Run Code Online (Sandbox Code Playgroud)
请记住,当资源是jar的一部分时,getResourceAsStream也可以正常工作,getResource返回一个通常用于创建文件的URL,可能会导致问题.
为了避免不可攻击的Java NPE(Java太可怕了),请考虑:
import scala.util.Try
import scala.io.Source
import java.io.FileNotFoundException
object Example {
def readResourceWithNiceError(resourcePath: String): Try[Iterator[String]] =
Try(Source.fromResource(resourcePath).getLines)
.recover(throw new FileNotFoundException(resourcePath))
}
Run Code Online (Sandbox Code Playgroud)
要获得有意义的FNFE.
对于生产代码,我还建议确保源再次关闭.
Moh*_*shi 27
对于Scala> = 2.12,使用Source.fromResource:
scala.io.Source.fromResource("located_in_resouces.any")
Run Code Online (Sandbox Code Playgroud)
import scala.io.Source
object Demo {
def main(args: Array[String]): Unit = {
val ipfileStream = getClass.getResourceAsStream("/folder/a-words.txt")
val readlines = Source.fromInputStream(ipfileStream).getLines
readlines.foreach(readlines => println(readlines))
}
}
Run Code Online (Sandbox Code Playgroud)
val source_html = Source.fromResource("file.html").mkString
Run Code Online (Sandbox Code Playgroud)