【发布时间】:2016-04-07 12:44:01
【问题描述】:
我阅读了一些在加载资源时遇到问题的人提出的问题。我已按照他们的说明进行操作(尽管这些说明实际上有所不同,这意味着两者都不正确 - 我都试过了)。
我创建了enum,以便在需要时为我加载资源。它很长,但我会分享它,以防有人从谷歌来到这里并可以使用它:
package cz.autoclient.GUI;
/**
* Enum of resources used for GUI. These resources are packed in .jar and are for internal use.
* Provides lazy-loaded Image and ImageIcon for comfort.
* @author Jakub
*/
public enum ImageResources {
ICON("IconHighRes.png");
//So according to [this guy](https://stackoverflow.com/a/17007533/607407) I
// should enter classpath beginning with slash to make sure it's absolute path from
// the root of my .jar
public static final String basepath = "/cz/autoclient/resources/";
//Cache everything to have less letters to write
public static final ClassLoader loader = ImageResources.class.getClassLoader();
public static final Class leclass = ImageResources.class;
//String is immutable so it's ok to make it a public constant
public final String path;
//These will fill up on demand when needed
private ImageIcon icon;
private Image image = null;
//If image has failed, we'll not try to load it again and will return null straight away
private boolean image_failed = false;
//Constructor concatenates the individual path with the global path
ImageResources(String path) {
this.path = basepath+path;
}
/** Loads, or just retrieves from cache, the image.
* @return Image (not necesarily a BufferedImage) or null on failure
*/
public Image getImage() {
//Lazy load...
if(image==null) {
//Since the .jar is constant (it's packed) we can
//Remember the image is unavailable
if(image_failed)
return null;
//Use whatever is stored in Icon if we have it
if(icon!=null) {
image = icon.getImage();
}
//Load from .jar
else {
try {
image = ImageIO.read(leclass.getResourceAsStream("/images/grass.png"));
}
//While only IOException is reported it also can throw InvalidArgumentException
// when read() argument is null
catch(Exception e) {
image_failed = true;
}
}
}
return image;
}
}
Full version on GitHub. 可能会发生变化。
由于此代码不起作用(由于无效的基本路径),我想知道一个通用的方法来查找 为什么资源没有加载 和 ClassLoader 在哪里寻找。
例如,当我从文件系统加载普通文件时遇到问题,我可以这样做:
File relativePath = new File("../my_test_image.png");
System.out.println(relativePath.getAbsolutePath());
我可以立即看到 Java 在哪里寻找以及我应该改变什么。如果我和其他人都知道使用资源的简单方法,那么就不需要问所有这些问题了:
- Getting a BufferedImage as a resource so it will work in JAR file
- loading BufferedImage with ClassLoader.getResource()
- java getResource() not working
- Resource loading in Java not working as it should
- How to correctly get image from 'Resources' folder in NetBeans
那么有没有办法打印我的资源路径转换成什么?
我尝试了什么:
【问题讨论】:
-
((URLClassLoader) (Thread.currentThread().getContextClassLoader())).getURLs();不适合你? -
打印了很多 Maven 依赖项。此外,结果实际上是文件系统绝对路径:pastebin.com/msK76bvB
-
leclass.getResourceAsStream("/images/grass.png")将尝试通过“images”包中的“leclass”类加载器加载“grass.png”。包需要与 leclass 类位于同一目录(或 .jar)中。 -
对我来说它不起作用,因为我正在运行在不同目录中运行的测试类(Maven)。但是图书馆如何处理这个问题?他们在测试类目录中运行没有问题...
标签: java netbeans embedded-resource