Java 路径 ImageIcon URL .JAR [英] Java Path ImageIcon URL .JAR

查看:19
本文介绍了Java 路径 ImageIcon URL .JAR的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可能已经尝试过了,没有任何效果..

I may have made of try, none works..

文件是:

/Users/Toto/Desktop/Titi/IUT/Java/TP2/project/src/fichierPointJava/img1.png

fichierPointJava 是包的名称.

当我位于包含 build.xml 的项目中时,我启动了 ant

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);

无论有没有this,不管有没有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.

您可以阅读更多关于 ClassLoader#getResourceJava 文档中的 Class#getResource.

You can read more about ClassLoader#getResource and Class#getResource in the javadocs.

确保您正在运行以创建 jar 的 ant 目标包含 *.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 路径 ImageIcon URL .JAR的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆