Getting a resource in a different project using classloader

蓝咒 提交于 2021-01-27 22:51:07

问题


Using the ClassLoader#getResource(), I need to access a file that is present in a project other than the one where my current code resides. How can this be done?

I'm using eclipse.

Directory Structure:

Root  
|-project1  
| |-package  
|   |-myResourceFile  
|-project2  
  |-package  
    |-myCodeFile  

I'm trying to get myResourceFile from myCodeFile, using myCodeFile.class.getClassLoader().getResource("../../project1/package/myResourceFile") but its always returning null. I do not want to add project1 to the classpath of project2. Though adding that also did not work.

With regards,


回答1:


It's a bad idea to attempt to read files from another project like that because it ties you to exactly that directory structure. You already did the first step in decoupling the projects by using getResource() instead of using the java.util.File API so you can go the full way as well.

In Eclipse you can add other projects to a projects' build path (Project Properties -> Java Build Path -> Projects). You should be able to read the other projects' files now.




回答2:


If you are using maven, then you can specify project1/package as a resource folder in the pom.xml of project2. You can theen use Classloader getResource method to get the resouce

http://maven.apache.org/plugins/maven-resources-plugin/examples/resource-directory.html



来源:https://stackoverflow.com/questions/3966996/getting-a-resource-in-a-different-project-using-classloader

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!