How to read files from resources folder in Scala?

前端 未结 6 936
渐次进展
渐次进展 2020-11-29 16:37

I have a folder structure like below:

- main
-- java
-- resources 
-- scalaresources
--- commandFiles 

and in that folders I have my files

6条回答
  •  误落风尘
    2020-11-29 17:01

    For Scala 2.11, if getLines doesn't do exactly what you want you can also copy the a file out of the jar to the local file system.

    Here's a snippit that reads a binary google .p12 format API key from /resources, writes it to /tmp, and then uses the file path string as an input to a spark-google-spreadsheets write.

    In the world of sbt-native-packager and sbt-assembly, copying to local is also useful with scalatest binary file tests. Just pop them out of resources to local, run the tests, and then delete.

    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}")
    

提交回复
热议问题