问题描述
我可能已尝试过,但没有效果..
I may have made of try, none works..
该文件为:
/Users/Toto/Desktop/Titi/IUT/Java/TP2/project/src/fichierPointJava/img1.png
fichierPointJava
是包的名称。
我发布了蚂蚁当我位于包含build.xml的项目中时
I launch the ant when I am situated in project which contains the build.xml
以下是我测试的代码:
URL urlImage1=this.getClass().getClassLoader.getResource("/src/fichierPointJava/img1.png");
URL urlImage1=this.getClass().getClassLoader.getResource("/fichierPointJava/img1.png");
URL urlImage1=this.getClass().getClassLoader.getResource("fichierPointJava/img1.png");
URL urlImage1=this.getClass().getClassLoader.getResource("/img1.png");
URL urlImage1=this.getClass().getClassLoader.getResource("img1.png");
System.out.println("Value = "+ urlImage1);
我做了一个带或不带的遗嘱
,有或没有 getClassLoader()
I made out a will with or without this
, and with or without getClassLoader()
希望有人能帮助我。
谢谢你
推荐答案
如果您有以下套餐布局
+---src
| img0.png
\---fichierPointJava
| img1.png
| <YourClass.java>
然后以下内容应该有效
// using the classloader in instance context
getClass().getClassLoader().getResource("img0.png");
getClass().getClassLoader().getResource("fichierPointJava/img1.png");
// using the classloader in class/static context
<YourClass>.class.getClassLoader().getResource("img0.png");
<YourClass>.class.getClassLoader().getResource("fichierPointJava/img1.png");
// using the class in instance context
getClass().getResource("../img0.png");
getClass().getResource("/img0.png");
getClass().getResource("img1.png");
getClass().getResource("/fichierPointJava/img1.png");
// using the class in static/class context
<YourClass>.class.getResource("../img0.png");
<YourClass>.class.getResource("/img0.png");
<YourClass>.class.getResource("img1.png");
<YourClass>.class.getResource("/fichierPointJava/img1.png");
当使用 ClassLoader
时,你需要通过资源的完整限定名称,即包括包名。
When using the ClassLoader
you need to pass the full qualified name of the resource, i.e including the package name.
当使用 Class
时,路径 - 如果不是以 /
开头 - 是相对于尝试加载资源的类所在的包,否则它是资源的绝对名称。
When using the Class
then the path - if not starting with /
- is relative to the package where the class which is trying to load the resource is located, otherwise it is the absolute name of the resource.
您可以阅读更多关于和在javadocs中。
You can read more about ClassLoader#getResource and Class#getResource in the javadocs.
确保蚂蚁正在运行以创建jar的目标包括 * .png
资源。您可以使用您选择的zip工具打开jar来验证这一点。不应包含目录 src
。
Make sure that the ant target you are running to create the jar include the *.png
resources. You can verify this by opening the jar with the zip-tool of your choice. The directory src
should not be included.
这篇关于Java Path ImageIcon URL .JAR的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!