我有一个如下所示的文件夹结构:
- 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
}
}
}
Scala 中的资源与 Java 中的资源完全一样。
最好遵循Java 最佳实践并将所有资源投入src/main/resources
and src/test/resources
.
文件夹结构示例:
testing_styles/
├── build.sbt
├── src
│ └── main
│ ├── resources
│ │ └── readme.txt
Scala 2.12.x && 2.13.x 读取资源
读取对象的资源Source提供了方法来自资源.
import scala.io.Source
val readmeText : Iterator[String] = Source.fromResource("readme.txt").getLines
阅读 2.12 之前的资源(由于 jar 兼容性,仍然是我的最爱)
要阅读资源,您可以使用getClass.getResource and getClass.getResourceAsStream .
val stream: InputStream = getClass.getResourceAsStream("/readme.txt")
val lines: Iterator[String] = scala.io.Source.fromInputStream( stream ).getLines
更好的错误反馈(2.12.x && 2.13.x)
为了避免无法调试的 Java NPE,请考虑:
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))
}
很高兴知道
请记住获取资源作为流当资源是某个资源的一部分时也能正常工作jar, 获取资源,它返回一个经常用于创建文件的 URL 可能会导致出现问题。
生产中
在生产代码中,我建议确保再次关闭源。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)