如何在Scala中将资源文件夹中的文件作为InputStream读取?

时间:2018-12-05 22:34:56

标签: scala

我具有以下目录结构。

- main
-- scala
-- resources
--- file.json

我想将file.json 读取为java.io.InputStream 。我知道我可以将其读为Source,但不知道如何获得InputStream

2 个答案:

答案 0 :(得分:2)

我使用以下方式。

getClass.getClassLoader.getResourceAsStream(resourceName)

答案 1 :(得分:0)

您在我写答案时回答了:

我提出此解决方案:

  def readJsonWithTry(filePath: String): Try[InputStream] = {
    Try {
      val lines = getClass.getClassLoader.getResourceAsStream(filePath)
      lines
      }
  }

  readJsonWithTry("resourceName") match {
    case Success(s) => s
    case Failure(f) => println(s"Failed, message is: $f")
  }