Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add a resource file in Grails application?

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 ?

like image 295
morgan Avatar asked Aug 27 '14 12:08

morgan


1 Answers

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

like image 51
Steinar Avatar answered Oct 31 '22 19:10

Steinar