我如何调试资源路径加载或一般的ClassLoader?

时间:2015-03-07 16:51:51

标签: java netbeans embedded-resource

我已经阅读了加载资源时遇到问题的人的一些问题。我已经按照他们的说明进行了操作(尽管这些说明实际上有所不同,这意味着要么是不正确的 - 我都试过了。)

我创建了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.可能会有变化。

由于此代码不起作用(由于无效的基本路径),我想知道找到为什么资源未加载哪里是{{1}的一般方法查看

例如,当我从文件系统加载普通文件时遇到问题,我可以这样做:

ClassLoader

我可以立即看到Java在哪里,我应该改变什么。如果我和其他人都知道用资源做一个简单的方法,那么就不需要问所有这些问题:

有没有办法打印我的资源路径转化为什么?

我尝试了什么:

1 个答案:

答案 0 :(得分:0)

所以看起来你总是可以通过这个声明获得当前路径:

System.out.println("  Path: \""+loader.getResource(".")+"\"");

对我来说,这给了:

  Path: "file:/C:/... path to project .../PROJECT_NAME/target/test-classes/"

这是运行测试的测试类的路径,而不是为其创建的实际类loader。我不认为这是一个错误。