Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing gradle resources from Java

I have a gradle-based java project with this structure

.
├── myproject
│      ├── src
│      |    └── main
│      |         ├── java
│      |         └── resources
│      |               └── myresource.xml
|      ├── build
|      |     ├── classes
|      |     |    └── main
│      |     |         └── myresource.xml
|      |     ├── resources

I'm trying to access some files in the resources folder using a ClassLoader, like this

ClassLoader.getSystemClassLoader().getResoure("/myresource.xml");

but it does not find the file.

The only way I have found to access those files is by exploring the known structure of the project

Path resourcesPath= FileSystems.getDefault().getPath(System.getProperty("user.dir"), "/src/main/resources/");

Any idea on what am I doing wrong?

like image 820
magomar Avatar asked Jul 24 '14 17:07

magomar


2 Answers

Well, it seems my difficulties came from another problem (resources not being copied to the proper places). Once I solved that problem, the ClassLoader was able to find my resources using either of these two forms:

ClassLoader.getSystemClassLoader().getResource("./myresource.xml");

ClassLoader.getSystemClassLoader().getResource("myresource.xml");

Edit: When using the jar embedded in other applications, the former solution do not work, use this in that case:

Thread.currentThread().getContextClassLoader().getResource("myresource.xml")
like image 176
magomar Avatar answered Oct 27 '22 07:10

magomar


http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getResource(java.lang.String)

For example something like MyMain.class.getResource("/config.txt") or use relative path when appropriate.

like image 44
Radim Avatar answered Oct 27 '22 07:10

Radim