Scala 不从资源文件夹中读取文件

标签 scala sbt intellij-15

为什么以下不看war-and-peace.txt来自 resources 的文件文件夹?

我项目中的文件夹结构是使用 Intellij 创建的标准 Scala 结构。

出于某种原因,当我将它放入 src/main/scala 时,它只会读取这个文件。 (即我的 Scala 代码在哪里),但是当我把它放在 src/main/resources 中时忽略了这个文件(在后一种情况下,我得到 java.lang.NullPointerException ,顺便说一句,当我尝试阅读 "/war-and-peace.txt"(带有前面的斜杠)时,我也得到了同样的异常(exception),以防您想提出建议)。

val file = new File(classLoader.getResource("war-and-peace.txt").getFile())

Source.fromFile(file).....

我在用
java version "1.8.0_101"
Java(TM) SE Runtime Environment (build 1.8.0_101-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.101-b13, mixed mode)

build.sbt:
name := "my-project"

version := "1.0"

scalaVersion := "2.11.8"

resourceDirectory in Compile := baseDirectory.value / "resources"

libraryDependencies += "junit" % "junit" % "4.12"

libraryDependencies += "org.scalatest" % "scalatest_2.11" % "2.2.4"

最佳答案

使用 getClass不是 classLoader并放 /在资源名称前面/war-and-peace.txt . war-and-peace.txt文件必须在资源文件夹 (src/main/resources) 中。

val file = getClass.getResource("/war-and-peace.txt").getFile()

Source.fromFile(file).getLines.foreach(println)

一行
Source.fromFile(getClass.getResource("/war-and-peace.txt").getFile).getLines().foreach(println)

getClass.getResourceAsStream 更可靠,因为当代码也打包在 jar 文件中时它也能工作
Source.fromInputStream(getClass.getResourceAsStream("/war-and-peace.txt")).getLines().foreach(println)

关于Scala 不从资源文件夹中读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40342910/

相关文章:

scala - 卡夫卡流: configuring `AdminClientConfig` or `ConsumerConfig` without overriding the values both

sbt - 在 sbt 项目中编译 Scala 2.10-RC3 宏

sbt - Windows操作系统中SBT构建工具中的global.sbt

SBT 挂起解决依赖关系

intellij-idea - IntelliJ IDEA 15 Ultimate,设置窗口中缺少其他设置

performance - 为什么Scala中foldLeft前面的过滤器很慢?

Scala - 获取绑定(bind)变量列表?

unit-testing - Scala、Scalatest 和 Maven 入门

java - 如何在 IntelliJ 中添加外部 jar 文件而不引用本地目录

java - Intellij -d 选项不起作用