Accessing gradle resources from Java

后端 未结 3 2178
一整个雨季
一整个雨季 2021-02-19 08:17

I have a gradle-based java project with this structure

.
├── myproject
│      ├── src
│      |    └── main
│      |         ├── java
│      |         └── resourc         


        
相关标签:
3条回答
  • 2021-02-19 08:37

    Maybe you should use it this way:

    
    Thread.currentThread().getContextClassLoader().getResource("myresource.xml")
    
    

    If i use ClassLoader.getSystemClassLoader().getResource("myresource.xml")

    When I use it as a jar package embedded in other applications, I still have no access to resources.

    0 讨论(0)
  • 2021-02-19 08:42

    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")
    
    0 讨论(0)
  • 2021-02-19 08:57

    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.

    0 讨论(0)
提交回复
热议问题