78

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");
Perception
  • 79,279
  • 19
  • 185
  • 195
Buddhi
  • 2,224
  • 5
  • 32
  • 43

22 Answers22

74

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.

yggdraa
  • 2,002
  • 20
  • 23
  • 25
    This answer is not applicable to Maven projects – Sym-Sym Feb 19 '15 at 22:18
  • 1
    @Sam What would be the solution for maven projects? – maja Apr 11 '15 at 19:11
  • 1
    This is because Intellij won't copy "non-resource" files to your target folder. Hence that file is nowhere to be found and loaded. – kervin Feb 11 '16 at 04:53
  • 11
    In case anybody is having trouble finding it, these days the setting is located at **Settings ▶ Build, Execution, Deployment ▶ Compiler ▶ Resource patterns** – Simon Morgan Apr 15 '16 at 14:40
  • 1
    Another potential cause is if the project is a gradle project intellij syncs with the build file, so the resources need correctly specifying there in order to be compiled into the files that are run in a debugging session. – user2219808 Jul 29 '16 at 22:34
  • 4
    @maja For maven projects you have to add resource includes like so https://maven.apache.org/plugins/maven-resources-plugin/examples/include-exclude.html - That did the trick for me. – AdrianVeidt Dec 11 '17 at 09:58
47

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.

Martin Algesten
  • 13,052
  • 4
  • 54
  • 77
36

Use the getResource method of the class' ClassLoader

URL url = ExchangeInterceptor.class.getClassLoader().getResource("GeoIP.dat");
Wins
  • 3,420
  • 4
  • 36
  • 70
18

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

MewX
  • 4,232
  • 1
  • 29
  • 38
12

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

Taras Melnyk
  • 3,057
  • 3
  • 38
  • 34
8

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.

merovin
  • 89
  • 1
  • 1
  • 4
    It does not point to a specific folder at all. It just points to the classpath. You should see it the other way round: the bin folder which you're talking about is part of the runtime classpath. – BalusC Apr 22 '12 at 23:15
  • well, I've tried to use the same method too and got the same error as the original poster. I fixed it by adding the files to the paths I mentioned, so I thought I should share this "discovery" – merovin Apr 22 '12 at 23:45
  • 2
    You just discovered one of the paths of the classpath. OP has it already in the classpath, OP was just accessing it with the wrong path. – BalusC Apr 23 '12 at 01:10
8

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

Max
  • 4,882
  • 2
  • 29
  • 43
  • BTW, looking back on this now...I don't necessarily know that I'd *recommend* this as a good solution, as the Gradle integration in this case seems rough. But if it works for you, great. – Max Apr 25 '18 at 21:49
5

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.

javamonkey79
  • 17,443
  • 36
  • 114
  • 172
5

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.

Akash Agarwal
  • 2,326
  • 1
  • 27
  • 57
3

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")
samet kaya
  • 105
  • 3
3

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

getClass().getClassLoader().getResource("./file.txt")
Stefan Zhelyazkov
  • 2,599
  • 4
  • 16
  • 41
2

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.

Peter Jamieson
  • 745
  • 5
  • 10
2

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, ...

iirekm
  • 8,890
  • 5
  • 36
  • 46
1

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
Pnemonic
  • 1,685
  • 17
  • 17
1

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
CodeToLife
  • 3,672
  • 2
  • 41
  • 29
0

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

shareef
  • 9,255
  • 13
  • 58
  • 89
0

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.

Asad-ullah Khan
  • 1,573
  • 18
  • 22
0

Strangely effective in my case (IJ 2022.1.4) was: close project (for example, quit IDEA), delete the /.idea folder completely (egg, rm -rd .idea), open project. When it re-imports the project, it runs as expected. Note: you loose about everything not included in gradle configs.

sergeych
  • 791
  • 7
  • 11
0

In intellij i had to Build > "Rebuild Project". It seems it didn't automatically see the files i added to the maven resources directory.

-1

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

  • This is not an actual answer please refer to this guide on how to answer: https://stackoverflow.com/help/how-to-answer –  Apr 15 '21 at 16:13
-3

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 
Semmel
  • 27
  • 5
-5

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".

Jakub Zaverka
  • 8,816
  • 3
  • 32
  • 48