views:

17

answers:

1

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,

A: 

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.

musiKk