假设你的资源目录如下:
+-----src
. | img0.png
. \-----fichierPointJava
. | img1.png
. | <YourClass.java>
你可以通过以下方式来获取资源:
// 在非静态方法中使用ClassLoader的getResource() getClass().getClassLoader().getResource("img0.png"); getClass().getClassLoader().getResource("fichierPointJava/img1.png"); // 在静态方法中使用ClassLoader的getResource <YourClass>.class.getClassLoader().getResource("img0.png"); <YourClass>.class.getClassLoader().getResource("fichierPointJava/img1.png"); // 在非静态方法中使用Class的getResource() getClass().getResource("../img0.png"); getClass().getResource("/img0.png"); getClass().getResource("img1.png"); getClass().getResource("/fichierPointJava/img1.png"); // 在静态方法中使用Class的getResource() <YourClass>.class.getResource("../img0.png"); <YourClass>.class.getResource("/img0.png"); <YourClass>.class.getResource("img1.png"); <YourClass>.class.getResource("/fichierPointJava/img1.png");
总结
- 当你使用ClassLoader的getResource()时,你需要传入完整的路径,包括包名。
- 当使用Class的getResource()时,如果传入的路径不以/开头时,则只要传入资源与当前类所在包的相对路径即可 ,否则依然要传入完整的路径。
最后,请确认你构建的Jar中包含了你的资源信息,你可以使用Zip工具打开查看。你可以在API中
ClassLoader#getResource和
Class#getResource查看更多的细节。