3

I am trying to list all the files within a subdirectory in my resources directory but I am getting a NullPointerException because the line

val testDataDir = getClass.getResource("/data")

is returning java.net.URL = null

Resources structure:

/resources
  /data
    file1.txt
    file2.txt
  fileX.txt

My code is based off of this blog's code examples: here

This is the code snippet I am using:

val testDataDir = getClass.getResource("/data")    
val folder = new File(testDataDir.getPath)
var testDataArr: ListBuffer[String] = new ListBuffer[String]
if (folder.exists && folder.isDirectory) {
  folder.listFiles.toList.foreach(file => testDataArr += file.toString)
}
Liondancer
  • 15,721
  • 51
  • 149
  • 255

1 Answers1

2

1) You can go with absolute path getClass.getResource("/src/main/resources/data/")

using scala REPL from the root of the project, and to load src/main/resources/fileX.txt

scala> val appConfig = getClass.getResource("/src/main/resources/fileX.txt")
testDataDir: java.net.URL = file:/Users/prayagupd/scala_project/src/main/resources/fileX.txt

Or, loading package,

scala> val testDataDir = getClass.getResource("/src/main/resources/data")
testDataDir: java.net.URL = file:/Users/prayagupd/scala_project/src/main/resources/data

It does not work with filename only inside src/main/resources,

scala> val testDataDir = getClass.getResource("fileX.txt")
testDataDir: java.net.URL = null

2) Or, you can set your resources in classpath(-cp),

scala -cp src/main/resources/ TestResources.scala

object TestResources {                                                                                                                                                                     

   def main(args: Array[String]) = {                                                                   
      println("testing resources")                                                                                
      val data = getClass.getResource("/data")                                                           
      println(data)                                                                   
   }                                                                               
}

It does work inside IDE too, as it loads from compiled version classpath

val resources = getClass.getResource("/data")
file:/Users/prayagupd/scala_project/target/test-classes/data
prayagupa
  • 30,204
  • 14
  • 155
  • 192