Java - class.getResource returns null

JavaUrl

Java Problem Overview


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 Solutions


Solution 1 - Java

For those who use Intellij Idea: check for Settings > Build, Execution, Deployment > Compiler > Resource patterns.

The setting contains all extensions that should be interpreted as resources. If an extension does not comply to any pattern here, class.getResource will return null for resources using this extension.

Solution 2 - Java

The path is relative to the classpath root and if you don't give an absolute path, it is looking in the same package as the class you're using (in this case ExchangeInterceptor). To find something in the root use /GeoIP.dat.

Solution 3 - Java

Use the getResource method of the class' ClassLoader

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

Solution 4 - Java

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

Solution 5 - Java

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");

Solution 6 - Java

If you're using Gradle and IntelliJ, and changing Resource patterns didn't work, and your resource roots are set correctly...you can try this:

enter image description here

Settings > Build, Execution, Delpoyment > Build Tools > Gradle > Runner > Delegate IDE build/run actions to gradle. (IntelliJ 2017.3.3)

Source: https://youtrack.jetbrains.com/issue/IDEA-176738#comment=27-2518612

Solution 7 - Java

Just in case someone still has problems to understand that:

.getResource() grants you access to the local bin folder. That means, your resources need to be located in YourProject/bin/package/. The root folder is YourProject/bin/ and can be accssed by adding the prefix / to the String argument, like iirekm said.

Solution 8 - Java

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.

Solution 9 - Java

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.

Solution 10 - Java

This is my example solution. Work for me.

The project structure:

•	Source Packages
   •	game
       •	Game.java
   •	game.images
       •	tas_right.png

In the game class:

URL path=this.getClass().getClassLoader().getResource("images/tas_right.png")

Solution 11 - Java

Where do you have put this GeoIP.dat? In the same package as ExchangeInterceptor, or in the "root" package. If in the same package, your code is OK, if in the root - add '/' prefix.

Maybe you're using M2Eclipse? If configured incorrectly, it also may result in such problems. Another cause of such problems may be: misconfigured classloaders, misconfigured OSGi, ...

Solution 12 - Java

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.

Solution 13 - Java

Instead of having the resource file in the same folder as your source files, create a resources folder parallel to the java source folder.

Before:

  • src
  • main
    • java
      • MyClass.java
      • file.bin
      • file.txt

After:

  • src
    • main
      • java
        • MyClass.java
      • resources
        • file.bin
        • file.txt

Solution 14 - Java

I was able to fix it by adding "./" to the beginning of the file like this:

getClass().getClassLoader().getResource("./file.txt")

Solution 15 - Java

I use Intellij version Ultimate 2019.3

Go to

> Settings -> Compiler -> Resource patterns.

Click ok. Rerun Application/Server.

In my case, i included the jks in the project!

enter image description here

Solution 16 - Java

say you have :

titleLabel.setIcon(new ImageIcon(getClass().getResource("/uz/assets/icon.png")));//wrong !!

rightclick on the folder(mine is assets) an set Mark Directory as Resources if you dont see that rightclick on project name and pickup Open module settings

enter image description here

Rightclick on resorces folder(assets in my case) and select 'Resources' Now go back to the above java instruction and remove path BUT leave / like:

titleLabel.setIcon(new ImageIcon(getClass().getResource("/icon.png")));// correct one

Solution 17 - Java

A warning to all using the Path or Paths classes in Java: if you are on the god forsaken operating system known as Windows you will not be able to use Path.of or Paths.get as this will put backslashes in your path which Java will attempt to load and promptly fail. Instead use this:

Path.of(paths...).toString().replace(File.separator, "/")

You should always use this as it is OS independent. If anyone has a better or built in way please comment, I was unable to find one.

Solution 18 - Java

I realized using new File(location) works just fine in #dev and can also access files outside the /project folder

Solution 19 - Java

In case of eclipse.

Just a hint. Your code could be correct, but your jre configuration not. I ran into the the same error, nothing helped, until i checked the eclipse settings.

Make sure, that you set your execution environment right.

Preferences -> Java -> Installed JREs -> use "jdk..." as compatible JRE 

Solution 20 - Java

First, you need to make sure you are accessing the right file on the right path. You can verify that by getClass().getResource("GeoIP.dat").getAbsolutePath().

Secondly, the path specifier is case-sensitive, so make sure your file is not named "geoIP.dat" or "GeoIP.DAT".

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBuddhiView Question on Stackoverflow
Solution 1 - JavayggdraaView Answer on Stackoverflow
Solution 2 - JavaMartin AlgestenView Answer on Stackoverflow
Solution 3 - JavaWinsView Answer on Stackoverflow
Solution 4 - JavaMewXView Answer on Stackoverflow
Solution 5 - JavaTaras MelnykView Answer on Stackoverflow
Solution 6 - JavaMaxView Answer on Stackoverflow
Solution 7 - JavamerovinView Answer on Stackoverflow
Solution 8 - Javajavamonkey79View Answer on Stackoverflow
Solution 9 - JavaAkash AgarwalView Answer on Stackoverflow
Solution 10 - Javasamet kayaView Answer on Stackoverflow
Solution 11 - JavaiirekmView Answer on Stackoverflow
Solution 12 - JavaPeter JamiesonView Answer on Stackoverflow
Solution 13 - JavaPnemonicView Answer on Stackoverflow
Solution 14 - JavaStefan ZhelyazkovView Answer on Stackoverflow
Solution 15 - JavashareefView Answer on Stackoverflow
Solution 16 - JavaCodeToLifeView Answer on Stackoverflow
Solution 17 - JavaAsad-ullah KhanView Answer on Stackoverflow
Solution 18 - JavaMemo 313 MediaSAView Answer on Stackoverflow
Solution 19 - JavaSemmelView Answer on Stackoverflow
Solution 20 - JavaJakub ZaverkaView Answer on Stackoverflow