2017-06-06 152 views
8

我正在使用Spring Boot和json-schema-validator。我試圖從resources文件夾中讀取一個名爲jsonschema.json的文件。我嘗試了幾種不同的方法,但是我無法使其工作。這是我的代碼。從Spring Boot中的資源文件夾讀取文件

ClassLoader classLoader = getClass().getClassLoader(); 
File file = new File(classLoader.getResource("jsonschema.json").getFile()); 
JsonNode mySchema = JsonLoader.fromFile(file); 

這是文件的位置。

enter image description here

在這裏,我可以看到在classes文件夾中的文件。

enter image description here

但是當我運行的代碼我碰到下面的錯誤。

jsonSchemaValidator error: java.io.FileNotFoundException: /home/user/Dev/Java/Java%20Programs/SystemRoutines/target/classes/jsonschema.json (No such file or directory) 

這是什麼我做錯了我的代碼?

+0

你可以試試這個? 'ClassLoader classLoader = getClass()。getClassLoader(); ());' – harshavmb

回答

9

很簡短的回答:你正在尋找你的財產在一個特定的類加載器的範圍,而不是你的目標類。這應該工作:

File file = new File(getClass().getResource("jsonschema.json").getFile()); 
JsonNode mySchema = JsonLoader.fromFile(file); 

而且,看到這一點:

附:如果項目已經在一臺機器上編譯,然後在另一臺機器上啓動,或者在Docker中運行應用程序,則可能會出現問題。在這種情況下,資源文件夾的路徑可能無效。在這種情況下,它會更好,在運行時確定的路徑到你的資源:

ClassPathResource res = new ClassPathResource("jsonschema.json");  
File file = new File(res.getPath()); 
JsonNode mySchema = JsonLoader.fromFile(file); 
+0

'getClass()。getResource(「jsonschema.json」)''返回'null'。我也試過'ClassPathResource res = new ClassPathResource(「jsonschema.json」)'',它只返回'jsonschema.json'。這與我使用Spring Boot有關嗎? – g3blv

+0

不,這是一種常見的做法 –

0

陷入同樣的​​問題,這可以幫助我

URL resource = getClass().getClassLoader().getResource("jsonschema.json"); 
JsonNode jsonNode = JsonLoader.fromURL(resource); 
+0

實際上,這與給出的答案几乎相同 有關更多詳細信息,請參閱https://stackoverflow.com/questions/14739550/difference-between-getclass-getclassloader-getresource-and-getclass -getres –