如何从Scala中的资源文件夹中读取文件?

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)

Scala 2.12.x

为了读取资源,对象Source提供了fromResource方法.

import scala.io.Source
val readmeText : Iterator[String] = Source.fromResource("readme.txt").getLines
Run Code Online (Sandbox Code Playgroud)

先前版本

要读取资源,可以使用getClass.getResourcegetClass.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,可能会导致问题.

更好的错误反馈(2.12.x)

为了避免不可攻击的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.

对于生产代码,我还建议确保源再次关闭.

  • 别忘了"关闭"来源 (3认同)
  • 在某些情况下,空指针:http://stackoverflow.com/questions/941754/how-to-get-a-path-to-a-resource-in-a-java-jar-file (2认同)

Moh*_*shi 27

对于Scala> = 2.12,使用Source.fromResource:

scala.io.Source.fromResource("located_in_resouces.any")
Run Code Online (Sandbox Code Playgroud)

  • 重要:使用`Source.fromResource`,你不会使用`getResourceAsStream`放置初始正斜杠. (13认同)
  • 请注意,这是2.12+ (6认同)

Sri*_*Sri 9

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)


fre*_*dev 7

Scala Onliner解决方案> = 2.12

val source_html = Source.fromResource("file.html").mkString
Run Code Online (Sandbox Code Playgroud)