如何访问具有相同名称的多个资源文件?

时间:2018-09-29 17:58:26

标签: java classpath

假设我有两个包p1和p2,它们的资源名为abc.propertiescom.example.p1\abc.propertiescom.example.p2\abc.properties

程序编译后,由于类路径的顺序,我只能使用com.example.p1\abc.properties访问getClass().getResource(“abc.properties”)

有什么方法可以访问另一个文件(com.example.p2\abc.properties)?

UPD::我发现打包的jar结构如下: p1-1.0.jar: com.example.p1 META-INF abc.properties p2-1.0.jar: com.example.p2 META-INF abc.properties 因此,实际上,getClass().getResource(“/com/example/p1/abc.properties”)这样的代码对我不起作用

1 个答案:

答案 0 :(得分:2)

默认情况下,资源是相对于正在使用的Class实例进行解析的-因此,如果您的课程位于软件包com.example.p1中,并且您使用的是getClass().getResource("abc.properties"),则最终会得到{{ 1}}。

要解决此问题,您可以使用绝对路径来解析资源-例如com/example/p1/abc.propertiesgetClass().getResource("/com/example/p1/abc.properties")。请注意,您需要在路径前加一个正斜杠,并用斜杠替换路径中的所有句点。