无法在jar中加载资源 [英] Cannot load resource in jar

查看:192
本文介绍了无法在jar中加载资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在jar中加载资源,这里是导出的jar:

I am trying to load a resource in a jar, here is the exported jar:

'main'是包含所有类的包,在其中一个类中我尝试加载background.png文件。在我的Eclipse项目中,我将资源放在res /文件夹下,我将其添加到构建路径中以包含它。当我尝试使用

'main' is the package with all my classes, and in one of those classes I am trying to load the background.png file. In my Eclipse project I put the resources under a "res/" folder, which I added to the build path to include it. When I try to use

new File("background.png");

找不到文件。
当我使用

It can't find the file. When I use

MyClass.class.getClass().getClassLoader().getResource("background.png");

它仍无法找到该文件。

推荐答案

包装的文件在jar中无法访问文件对象。

Files packaged in a jar can't be accessed as File objects.

当你尝试

MyClass.class.getClass().getClassLoader().getResource("background.png");

你实际上是在使用 ClassLoader java.lang.Class 而不是 main.MyClass 可能无法找到资源(如果是系统类加载器)。尝试

you are actually using the ClassLoader of java.lang.Class and not of main.MyClass which may not be able to find the resource (in case it is the system classloader). Try

MyClass.class.getClassLoader().getResource("background.png");

而不是。

这篇关于无法在jar中加载资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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