Java - class.getResource returns null

2019-01-04 02:37发布

I am using the following to get the URL of this particular file, but it returns null. Does anyone have any suggestions as to the problem or an alternate way to do this?

URL url = ExchangeInterceptor.class.getResource("GeoIP.dat");

标签: java url
13条回答
forever°为你锁心
2楼-- · 2019-01-04 02:44

I've faced with the similar problem. From Java SE API for getResource​(String name) :

If the name begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of the name following the '/'.

So I've added '/' before my directory : MyClass.class.getResource("/dir_name/").

In your case try to add '/' before your file name:

URL url = ExchangeInterceptor.class.getResource("/GeoIP.dat");

查看更多
淡お忘
3楼-- · 2019-01-04 02:45

Use the getResource method of the class' ClassLoader

URL url = ExchangeInterceptor.class.getClassLoader().getResource("GeoIP.dat");
查看更多
We Are One
4楼-- · 2019-01-04 02:46

No, that is the right way afaik. Make sure the resource is on your classpath. This is often the cause of these types of problems.

查看更多
可以哭但决不认输i
5楼-- · 2019-01-04 02:49

I solved this problem by pointing out the resource root on IDEA.

Initially the directory was so and the icon was a plain folder icon

Before

enter image description here

Right click on a directory (or just the project name) -> Mark directory As -> Resource Root.

After

after

Recompile & rejoice :P

查看更多
Luminary・发光体
6楼-- · 2019-01-04 02:49

The file needs to be in the classpath, e.g.: -

bin/my/package/GeoIP.dat

The / prefix seems to be a lie. The following would work.

URL url = ExchangeInterceptor.class.getResource("my/package/GeoIP.dat");

I suspect the issue is that you do not have the file in the classpath.

查看更多
萌系小妹纸
7楼-- · 2019-01-04 02:52

While using IntelliJ, I generated the project as a JavaFX app and then added maven framework support to it. Turns out, I then placed my resource in src/main/resources and had to add ./ behind every resource name that while using them in the code.

Also as stated in a previous answer, only loading the resource by a classLoader worked.

So for me, the final URL loading was done using:

URL url = getClass().getClassLoader().getResource(String.format(".%ssample.fxml", File.separatorChar));

The File.separatorChar returns / on *nix and \ on windows.

查看更多
登录 后发表回答