4

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,

Unknown
  • 41
  • 1
  • 2

2 Answers2

2

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
  • 14,751
  • 4
  • 55
  • 82
1

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

athreya86
  • 98
  • 1
  • 1
  • 8
  • Doesnt make sense this maven apache method of accessing resources from nother project because it doesnt specify which project it is how will it know – Ishmael Mavor Raines Jun 07 '22 at 19:39