2017-05-29 57 views
0

我想列出我resources目錄的子目錄中的所有文件,但我得到一個NullPointerException因爲該行上市資源的子目錄中階NullPointerException異常

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

正在恢復java.net.URL = null

資源結構:

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

我的代碼是bas編過這個博客的代碼示例:here

這是我使用的代碼片段:

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) 
} 
+0

你真的創建了一個名爲:val? 你到底在想什麼? – Stultuske

+1

可能是這個問題的副本: https://stackoverflow.com/questions/3803326/this-getclass-getclassloader-getresource-and-nullpointerexception – Alexey

+0

你使用的是什麼版本的scala? –

回答

1

1)您可以使用Scala的REPL與絕對路徑getClass.getResource("/src/main/resources/data/")

去從項目的根源,並加載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 

或者,裝載包,

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

它不與文件名裏面只有src/main/resources工作,

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

2)或者,你可以設置你的resources在類路徑(-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)                 
    }                    
} 

它也可以在IDE內部工作,因爲它loads from compiled version classpath

val resources = getClass.getResource("/data") 
file:/Users/prayagupd/scala_project/target/test-classes/data