开发者

Getting a resource in a different project using classloader

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?

开发者_StackOverflow

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,


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜