假设我有两个包p1和p2,它们的资源名为abc.properties
:com.example.p1\abc.properties
和com.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”)
这样的代码对我不起作用
答案 0 :(得分:2)
默认情况下,资源是相对于正在使用的Class
实例进行解析的-因此,如果您的课程位于软件包com.example.p1
中,并且您使用的是getClass().getResource("abc.properties")
,则最终会得到{{ 1}}。
要解决此问题,您可以使用绝对路径来解析资源-例如com/example/p1/abc.properties
或getClass().getResource("/com/example/p1/abc.properties")
。请注意,您需要在路径前加一个正斜杠,并用斜杠替换路径中的所有句点。