我有一个如下所示的文件夹结构:
- main
-- java
-- resources
-- scalaresources
--- commandFiles
在这些文件夹中,我有我必须读取的文件。代码如下:
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
}
}
}
发布于 2016-12-08 11:32:49
对于Scala >= 2.12,使用Source.fromResource
scala.io.Source.fromResource("located_in_resouces.any")
发布于 2018-11-19 13:53:24
Scala >= 2.12的单行解决方案
val source_html = Source.fromResource("file.html").mkString
发布于 2018-08-04 14:18:08
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))
}
}
https://stackoverflow.com/questions/27360977
复制