【问题标题】:Getting null while loading resources in executable jar在可执行 jar 中加载资源时获取 null
【发布时间】:2014-06-09 10:00:35
【问题描述】:

我有一个基于桌面的 maven 项目,在该项目中,我在很多地方都从资源文件夹中加载图像,如下所示:

JLabel Footer = new JLabel(new ImageIcon(this.getClass().getClassLoader().getResource("Images/gloBOT_logo.png")));

Images 文件夹在 src/main/resources

这段代码在 Eclipse IDE 中运行良好,但是当我运行我的可执行 jar 时,我得到 NullPointerException,因为它无法加载图像。

谁能建议我如何在 Eclipse IDE 中从资源文件夹加载图像,并且它也应该可以通过可执行 jar 工作?

【问题讨论】:

    标签: java maven jar resources executable


    【解决方案1】:

    您可以尝试在网址前添加/

    ImageIcon(this.getClass().getClassLoader().getResource("/Images/gloBOT_logo.png")));
    

    【讨论】:

    • 您的 jar 文件中是否存在图像?
    • 是的,图片也在maven创建的classes文件夹中
    【解决方案2】:

    显然,名称区分大小写,您可能需要在开头添加 /。如果这仍然不起作用,请确保文件在正确的位置(我认为它应该是 project/build/classes/Images/* )

    【讨论】:

    • 嗨,我试过了,是的,文件在正确的位置,但是在运行 jar 时它仍然无法正常工作..:(
    【解决方案3】:

    你可以做的就是使用这样的东西:

    ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();
    
    BufferedImage buffLogo = null;
    try {
        buffLogo = ImageIO.read( currentClassLoader.getResourceAsStream( "src/main/resources/Images/gloBOT_logo.png" ) );
    }catch ( IOException ex ) {
        //exception catching and handling goes here.
    }
    
    JLabel Footer = new JLabel( new ImageIcon( buffLogo ) );
    

    使用Class和ClassLoader加载资源有很大区别,我不太清楚如何解释,但我希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-03
      • 2015-09-18
      • 2011-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多