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

如何从Scala中的resources文件夹中读取文件?,scala,scala-collections,Scala,Scala Collections,我的文件夹结构如下所示: - main -- java -- resources -- scalaresources --- commandFiles 在这些文件夹中,我有我必须阅读的文件。 代码如下: def readData(runtype: String, snmphost: String, comstring: String, specificType: String): Unit = { val realOrInvFile = "/commandFiles/snmpcmds

我的文件夹结构如下所示:

- 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
src/test/resources

文件夹结构示例:

testing_styles/
├── build.sbt
├── src
│   └── main
│       ├── resources
│       │   └── readme.txt
Scala 2.12.x&&2.13.x读取资源 要读取资源,对象Source提供方法fromResource

import scala.io.Source
val readmeText : Iterator[String] = Source.fromResource("readme.txt").getLines
阅读2.12之前的参考资料(由于jar兼容性,我仍然最喜欢) 要阅读资源,可以使用getClass.getResourcegetClass.getresourceastream

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的一部分时,getResourcesStream也可以正常工作,getResource返回一个URL,该URL通常用于创建文件,这可能会导致出现问题

生产中
在生产代码中,我建议确保再次关闭源代码。

对于Scala>=2.12,请使用
source.fromResource

scala.io.Source.fromResource("located_in_resouces.any")
Scala>=2.12的在线解决方案 对于Scala2.11,如果getLines不能完全满足您的需要,您还可以将jar中的a文件复制到本地文件系统

下面是一个snippit,它从/resources读取二进制google.p12格式的API密钥,将其写入/tmp,然后使用文件路径字符串作为输入

在和的世界中,复制到本地对于scalatest二进制文件测试也很有用。只需将它们从资源中弹出到本地,运行测试,然后删除即可

import java.io.{File, FileOutputStream}
import java.nio.file.{Files, Paths}

def resourceToLocal(resourcePath: String) = {
  val outPath = "/tmp/" + resourcePath
  if (!Files.exists(Paths.get(outPath))) {
    val resourceFileStream = getClass.getResourceAsStream(s"/${resourcePath}")
    val fos = new FileOutputStream(outPath)
    fos.write(
      Stream.continually(resourceFileStream.read).takeWhile(-1 !=).map(_.toByte).toArray
    )
    fos.close()
  }
  outPath
}

val filePathFromResourcesDirectory = "google-docs-key.p12"
val serviceAccountId = "[something]@drive-integration-[something].iam.gserviceaccount.com"
val googleSheetId = "1nC8Y3a8cvtXhhrpZCNAsP4MBHRm5Uee4xX-rCW3CW_4"
val tabName = "Favorite Cities"

import spark.implicits
val df = Seq(("Brooklyn", "New York"), 
          ("New York City", "New York"), 
          ("San Francisco", "California")).
          toDF("City", "State")

df.write.
  format("com.github.potix2.spark.google.spreadsheets").
  option("serviceAccountId", serviceAccountId).
  option("credentialPath", resourceToLocal(filePathFromResourcesDirectory)).
  save(s"${googleSheetId}/${tabName}")

可以从scala中的资源文件夹访问所需文件,如下所示

val file = scala.io.Source.fromFile(s"src/main/resources/app.config").getLines().mkString

如果使用getResource并将其转换为文件,会出现什么样的问题?你能提供一个链接吗?在某些情况下,一个空指针:这段代码可能正在为getResourceAsStream留下打开的处理程序。别忘了关闭源代码谢谢!Byt类型在更好的错误反馈(2.12.x)部分不匹配。那么内存泄漏呢?资源不应该关闭吗?重要提示:使用
Source.fromResource
时,您不会使用
getResourceAsStream
时的初始正斜杠。请注意,这是2.12+版本2.10如何?为什么不接受Andreas Neumann提供的答案?如果您有任何后续问题,请对此进行评论-1.当您从网站上复制时,请发布一个指向原作者的链接。在应得的地方给予赞扬。参考:当代码相同时,并不意味着复制正确。这不适用于构建的jar
import java.io.{File, FileOutputStream}
import java.nio.file.{Files, Paths}

def resourceToLocal(resourcePath: String) = {
  val outPath = "/tmp/" + resourcePath
  if (!Files.exists(Paths.get(outPath))) {
    val resourceFileStream = getClass.getResourceAsStream(s"/${resourcePath}")
    val fos = new FileOutputStream(outPath)
    fos.write(
      Stream.continually(resourceFileStream.read).takeWhile(-1 !=).map(_.toByte).toArray
    )
    fos.close()
  }
  outPath
}

val filePathFromResourcesDirectory = "google-docs-key.p12"
val serviceAccountId = "[something]@drive-integration-[something].iam.gserviceaccount.com"
val googleSheetId = "1nC8Y3a8cvtXhhrpZCNAsP4MBHRm5Uee4xX-rCW3CW_4"
val tabName = "Favorite Cities"

import spark.implicits
val df = Seq(("Brooklyn", "New York"), 
          ("New York City", "New York"), 
          ("San Francisco", "California")).
          toDF("City", "State")

df.write.
  format("com.github.potix2.spark.google.spreadsheets").
  option("serviceAccountId", serviceAccountId).
  option("credentialPath", resourceToLocal(filePathFromResourcesDirectory)).
  save(s"${googleSheetId}/${tabName}")
val file = scala.io.Source.fromFile(s"src/main/resources/app.config").getLines().mkString