Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

defining root classpath for class.getResource()

I'm using java in Eclipse (windows), and I'm trying to use:

myClass.getResource("/image.jpg"), 

While image.jpg exists in the root loacation "myProject/". It returns null.

I checked many other threads but none of them resolved my issue.

So I tried to evaluate this:

this.getClass().getResource("/").getPath();

and it returned "myProject/build/classes".

So I checked the project's configuration for this dir, and found the exact same dir under

Java Build Path --> Source --> Default output folder

My questions are:

  1. why is the default dir of my resources is the output folder?

  2. As mentioned, I want to get a resource from another folder, but attempts to call "/../" aren't working... How can I then load other resources which are not nested in my classes dir? (I can change my output dir, but I think it will be very ugly...)

like image 584
user1028741 Avatar asked Sep 30 '13 21:09

user1028741


People also ask

What does class getResource do?

The getResource() method of java Class class is used to return the resources of the module in which this class exists. The value returned from this function exists in the form of the object of the URL class.

What is the root of the classpath?

Currently src is your root classpath.

How does getResource work in Java?

The getResource method finds a resource with the specified name. It returns a URL to the resource or null if it does not find the resource. Calling java. net.


1 Answers

You must put them in the root of "src/" folder ;-)

SRC/ folder is compiled to BUILD/CLASSES/, so all you put in src/* goes to classes/*

like image 119
angel_navarro Avatar answered Oct 06 '22 16:10

angel_navarro