SLY
SLY

Reputation: 535

How to get access multiple resource files with the same name?

Suppose I have two packages p1 & p2 with resource named abc.properties: com.example.p1\abc.properties and com.example.p2\abc.properties.

After the program compiled I can only access to com.example.p1\abc.properties using getClass().getResource(“abc.properties”), because of classpath order.

Is there any way to get access to another file (com.example.p2\abc.properties)?

UPD: I found packaged jar structure the following: p1-1.0.jar: com.example.p1 META-INF abc.properties p2-1.0.jar: com.example.p2 META-INF abc.properties So, in fact, code like this getClass().getResource(“/com/example/p1/abc.properties”) didn't worked for me

Upvotes: 1

Views: 1803

Answers (1)

apetranzilla
apetranzilla

Reputation: 5959

By default, resources are resolved relative to the Class instance being used - so if your class is in the package com.example.p1 and you use getClass().getResource("abc.properties"), you will end up with com/example/p1/abc.properties.

To fix this, you can use absolute paths to resolve resources - e.g. getClass().getResource("/com/example/p1/abc.properties") or getClass().getResource("/com/example/p2/abc.properties"). Note that you need to precede the path with a forward slash and replace any periods in the path with a slash.

Upvotes: 2

Related Questions