Scala does not read file from resources folder

rapt picture rapt · Oct 31, 2016 · Viewed 7.2k times · Source

Why does the following not read the war-and-peace.txt file from the resources folder?

The folder structure in my project is the standard Scala structure that is created be Intellij.

For some reason it only reads this file when I put it in the src/main/scala (i.e. where my Scala code is), but ignores this file when I put it in the src/main/resources (in the latter case I am getting java.lang.NullPointerException, BTW I am getting the same exception also when I try to read "/war-and-peace.txt" (with a preceding slash) in case you were thinking to suggest it).

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

Source.fromFile(file).....

I am using

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"

Answer

pamu picture pamu · Oct 31, 2016

Use getClass not classLoader and put / in front of the resource name /war-and-peace.txt. war-and-peace.txt file must be in resources folder (src/main/resources).

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

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

in one line

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

getClass.getResourceAsStream is more reliable as it works when the code is packaged inside a jar file also

Source.fromInputStream(getClass.getResourceAsStream("/war-and-peace.txt")).getLines().foreach(println)