IntelliJ IDEA - getClass().getResource("...") return null
Asked Answered
C

15

44

I'm using IntelliJ IDEA 13.1.5, I used to work with Eclipse. I'm working on JavaFX application, I try to load FXML file within my MainApp class using getClass().getResource(). I read the documentation and I try several idea, at the end I have null.

This is the hierarchy :

dz.bilaldjago.homekode.MainApp.java

dz.bilaldjago.homekode.view.RootLayout.FXML

This is the code snippet I used:

FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("view/RootLayout.fxml"));

I tried other solution such giving the url from the root and using the classLoader

the result is the same. Any idea please

Coldshoulder answered 12/10, 2014 at 17:38 Comment(2)
possible duplicate of Java - class.getResource returns nullDowne
Note that this might be an IntelliJ bug. See youtrack.jetbrains.com/issue/IDEA-119280 for details. - Here, everything works for tests, but not for the real run. The solution on my side was to copy everything from out/production/resources to out/production/classes.Guadalcanal
R
29

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

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

Recompile & rejoice :P Hope this working for you~

Rialto answered 16/10, 2016 at 0:28 Comment(4)
did not work for me, i changed the Compiler resource patterns. Made the resource folder both as the root folder of my project and then the working folder where my Class is and still didn't work! please help. I am using intellijDail
@AVERAGE Hi, I don't think that would be a problem. Have you tried re-creating a project, and redo your operation? If it still doesn't work, please post your detailed operation steps. That would be helpful for solving your issue.Rialto
for me, it worked if it's "src/resources" next to "src/main" path, but got null if in "resources" pathAnastaciaanastas
My sample program start working and that sample "HELLO" window is appearing but even though now the error is still there i.e->"Argument 'getClass().getResource("sample.fxml")' might be null"Shadbush
B
27

TL; DR;

  1. Put your resources in resources folder.

  2. Use them with one slash before their names: getClass().getResource("/myfont.ttf");

Long Story;

If you are using Intellij IDEA and you created a Maven project, you should put your resources in resources folder (as marked as resource root by intellij itself) and these resource go to the root of your compiled app.

I mean, /resources/myfont.ttf will go to /myfont.ttf in the resulting build.

So you should get it via /myfont.ttf and not myfont.ttf. Use it like this:

getClass().getResource("/myfont.ttf");

No need to change anything else. Just this one helped me.

Becca answered 1/9, 2019 at 11:47 Comment(1)
one slash before their names thanks, I was missing the leading slash...Blastoderm
S
25

For those who use Intellij Idea: check for Settings -> 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.

Salespeople answered 12/10, 2014 at 17:51 Comment(8)
I add fxml files using this pattern ?*.fxml but the result is the same!Coldshoulder
Why "?*.fxml" and not "*.fxml" or "view:*" - all files and folders within the directory view. see : jetbrains.com/idea/webhelp/compiler.html#patternSalespeople
I follow the same pattern exist in the Resources fieldColdshoulder
it doesn't make any change!Coldshoulder
I had same kind of issue with Jidea 14.1.1 and after updating resource pattern it solve the problem. :)Hardback
If adding the pattern did not help, try the answer in https://mcmap.net/q/82933/-java-class-getresource-returns-nullBede
@Coldshoulder did you manage to fix this problem? As i am experiencing the same issue right nowDail
Same here: I'm having this same problem I'm not managing to get it sorted out. I've already tried to change the Resource Patterns.Drily
O
4

if your project is a maven project, check the target code to see whether your .fxml file exist there. if it's not there ,just add

<resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.xml</include>
            </includes>
            <filtering>true</filtering>
        </resource>
    </resources>

in your pom.xml

Oakes answered 20/1, 2018 at 8:48 Comment(3)
Other than the methods mentioned above, this is a key point if use Maven. Never forget to load the pom.xml file and write the resource node in build node.Shemikashemite
applies to Kotlin as well.Latoyialatreece
It worked for me. Look here: maven.apache.org/plugins/maven-resources-plugin/examples/…Parodic
P
4

first, you need to set src and resource folders for IntelliJ.

see the icon near the java(blue) and resources(yellow 4 lines) folder.

enter image description here

right-click on java folder and select sources root enter image description here

and right-click on java folder and select resource root enter image description here

after that create the same package in the java folder and resource folder.

for example: packages -> org.example enter image description here

├─ src
   ├─ main
       ├─ java
       |  └─ com
       |      └─ example
       |           └─ A.class
       |
       └─ resources  
          └─ com
              └─ example
                    └─ fxml
                         └─ AFXML.fxml

in A.class you can use this.

Java

 FXMLLoader loader = new FXMLLoader(getClass().getResource("fxml/AFXML.fxml"));
 Parent root = loader.load();

Kotlin

 val loader = FXMLLoader(javaClass.getResource("fxml/AFXML.fxml"))
 val root = loader.load<Parent>()

or

 val loader = FXMLLoader(A::class.java.getResource("fxml/AFXML.fxml"))
 val root = loader.load<Parent>()
Parhe answered 6/12, 2020 at 22:53 Comment(0)
U
2

If your project is Gradle, check Settings -> Build, Execution, Deployment -> Gradle -> Build and run section. Ensure that "Build and run using" option is "Gradle".

Intellij IDEA's compiler doesn't copy "resources" to build dir nor to tests classpath. Also, it unexpectedly uses dummy "out" dir instead of "build".

UPDATED: only 1 option "Build and run using" is enough to set to Gradle.

Unbridle answered 14/5, 2020 at 16:3 Comment(0)
F
2

Very frustrating. What also happens is that the directory containing the resources are sometimes created as:

 └── resources
     └── my.tests             
           ├── t1.txt
           └── t2.txt

instead of:

 └── resources
     └── my
          └── tests
              ├── t1.txt
              └── t2.txt

The solution is to just manually recreate the directory structure so that it resembles the second example.

I also recommend to to troubleshoot your tests on the command line (with mvn clean test) if you're using maven to eliminate the chances of this being an IDE issue.

Freshman answered 18/6, 2021 at 8:49 Comment(1)
Another pitfall of IntelliJ, if you try to create directory structure as explained above, is that IntelliJ will automatically convert them to package structure (my.tests). This happens in IntelliJ's default view - Project view. The only way to create directories under resources is to switch to the Project Files view. Only then you are able to crate a proper directory structure...Pianism
L
1

In my case, ClassLoader helped

Class testClass = getClass();
URL url = testClass.getClassLoader().getResource(/fileName);
Ledoux answered 24/2, 2022 at 15:42 Comment(2)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Objectivism
Furthermore, there must not be a / at the beginning of fileName.Guadalcanal
R
0

As per suggestion, updated answer.

Step-1

  1. Right click on project
  2. Click on Mark Directory as
  3. Click on Sources Root

Step-2

  1. Click on File in Menu Bar
  2. Click on Project Structure… to open settings panel

Step-3

  1. Click on Modules tab
  2. As you see there isn’t any resources folder added as Content Root
  3. We need to add resources folder into it

Step-4

  1. Make sure to click on resource folder
  2. Click on Resources tab after that
  3. You will see resources folder added as Resource Folders in right panel

Re-run your java program and now it should work.

<---Previous Answer---->

Fixed similar issue today by adding resources folder into Resource Tab in IntelliJ IDE

Hope this helps. Also, details tutorial.

Runoff answered 8/2, 2020 at 17:40 Comment(2)
Thanks for answering, I don't proved if it's the correct answer ;) Linking images is not a well seen behaviour on stackoverflow. Can you describe what you have done? Perhaps in a list style: 1.) click here 2.) press the button or arrow style "ressources->edit"Chink
Thanks for suggestion @Chink - I'm new to stackoverflwo community.. Updated answer.Runoff
B
0

In Project Structure > Project you have to make sure Project compiler output: has its value filled in. In my case it did not. Point it to the ./target or ./bin (whatever you have) directory in your project.

Brushoff answered 3/5, 2021 at 8:50 Comment(0)
A
0

I used below code to access the file from resource folder in spring application. I used classLoader.getResourceAsStream(FileName) instead of getClass().getResourceAsStream(FileName), Hope this would help to access the file residing in resource folder.

String fileName = "./file.txt";
ClassLoader classLoader = getClass().getClassLoader();
InputStream inputStream = classLoader.getResourceAsStream(fileName);

I resolved file access so thought to share with all .
Abstractionism answered 24/9, 2021 at 11:47 Comment(0)
P
0

I had this same problem and tried all of the answers to this post. I finally found an answer on a different forum that works. This was the code I put into the build section of pom.xml

<resources>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>true</filtering>
        </resource>
    </resources>

It is important to make sure the directory section is the directory of the resource class, not the main class.

I also changed my compiler settings as was suggested in another comment. I found this answer on a post here: https://javawithus.com/en/classloadergetresource-returns-null/

Pickmeup answered 8/3, 2022 at 21:2 Comment(0)
P
-1

Windows is case-sensitive, the rest of the world not. Also an executable java jar (zip format) the resource names are case sensitive.

Best rename the file

view/RootLayout.FXML

to

view/RootLayout.fxml

This must be done by moving the original file away, and creating a new one.

Also compile to a jar, and check that the fxml file was added to the jar (zip file). When not IntelliJ resource paths are treated by an other answer.

By the way this is path relative to the package path of getClass(). Be aware if you extended this class the full path changes, better use:

MainApp.class.getResource("view/RootLayout.fxml")
Pulcheria answered 20/12, 2017 at 13:38 Comment(0)
C
-1

Use this syntax:

("../view/RootLayout.fxml"))
Cohlier answered 28/12, 2021 at 5:52 Comment(1)
completely wrong - periods are not supported in resource lookup!Abort
D
-2

I gave up trying to use getClass().getResource("BookingForm.css"));

Instead I create a File object, create a URL from that object and then pass it into getStyleSheets() or setLocation() File file = new File(System.getProperty("user.dir").toString() + "/src/main/resources/BookingForm.css");

scene.getStylesheets().add(folder.toURI().toURL().toExternalForm());

Dail answered 20/12, 2017 at 13:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.