wirtuotition
wirtuotition

Reputation: 23

Not able to get resource, classloader and class returns target path

I am trying to get a properties file from /src/main/resources/properties/ but for some reason the following code returns the path of target classes instead of src files. Can you please help?

System.out.println(PropTest.class.getResource("/properties/app.properties"));
System.out.println(PropTest.class.getClassLoader().getResource("properties/app.properties"));
ClassLoader classloader = Thread.currentThread().getContextClassLoader();
System.out.println(classloader.getResource("properties/app.properties"));
PropTest prop=new PropTest();
System.out.println(prop.getClass().getResource("/properties/app.properties"));

Each line gives the same output which is:

file:/C:/Users/b./eclipse-workspace/ordermonitoring/target/classes/properties/app.properties
file:/C:/Users/b./eclipse-workspace/ordermonitoring/target/classes/properties/app.properties
file:/C:/Users/b./eclipse-workspace/ordermonitoring/target/classes/properties/app.properties
file:/C:/Users/b./eclipse-workspace/ordermonitoring/target/classes/properties/app.properties

Upvotes: 1

Views: 2254

Answers (2)

Sibin S V
Sibin S V

Reputation: 26

The behavior is correct. The resources will be loaded from class path. There wont be any src folder at runtime. What you can do is make the /src/main/resources as a source folder (if you are not using maven) so that the properties will be copied to target folder.

Upvotes: 1

Binu
Binu

Reputation: 784

This is the expected behaviour. For maven projects, while running, project is build and is kept in target folder always. you can also change this folder by some configuration. From this target folder, your application runs and thus your path shown in classloader.getResource() method. If you are building a jar , then your resources will be inside the jar and is always available. So classloader.getResource() will be working fine always.

Upvotes: 0

Related Questions