I'm using Grails 2.4.3 and for my project, I need to load a resource file from a .java in /src/java/com/company/MyClass.java
I tried the following code :
ClassLoader.getSystemResourceAsStream("myfile.txt")
I tried to put the file everywhere in the project but it doesn't seem to find it.
It worked when I put the file in target/classes during the compilation. But it's not viable (I can't do this at every deployment)
How can I declare resources in a grails app to use in Java code ?
There is no dedicated resource directory for classpath resources, but resources are included from the source directories.
You can for instance place your resources in (preferably a sub-directory of) grails-app/conf
or src/java
.
You might run into problems loading them with the system class-loader (who knows what class loader magic is happening in the web application), but the following works fine for me:
def myFileContents = getClass().getResource('/mydir/myfile.txt').text
One final note, if the file is a java or groovy file, and you don't want it to compile (I ran into this case some time ago), then you have the option to include it directly in the correct web application directory: web-app/WEB-INF/classes/mydir/myfile.groovy
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With