为什么以下不看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/