'Java play framework null pointer exception in reflection giving file
In java play framework project I do not figure out in retrieving file sample.txt in same package of my current controller class.
I try with this command:
URL resource = MyController.class.getResource("text.txt");
This is my current project structure:
- app
---- test
--------- controller
------------- MyController
------------- text.txt
I have tried with a similar command:
InputStream resource = MyController.class.getResourceAsStream("text.txt");
or
ClassLoader cl = getClass().getClassLoader();
File file = new File(cl.getResource("text.txt").getFile());
Same null pointer.
How can I solve it?
Solution 1:[1]
Maybe the instruction : cl.getResource("text.txt").getFile() in play framework do not get the file in the path getClass().getClassLoader(). It can be a visibility problem. Play framework can not access to all project folder via getClassLoader(). Try to put the file into conf folder and get it with Play.application().resourceAsStream("file.txt");
Solution 2:[2]
Controller directory it is not the execution directory, it is only for the source code files.
Work directly with ressources, for your case, intenal usages, see https://www.playframework.com/documentation/2.8.x/sbtCookbook#Configure-externalized-resources
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | dav |
| Solution 2 | Jérôme C. |
