Search code examples
javaintellij-ideanullpointerexceptionresources

Why is one java class in same directory not able to find resource while other can?


I have a project structure like this:

main-directory
    src
       code
          images
          javaFile1.java
          test.java

The compiled project structure is like this:

out
  artifacts
  production
    main-directory
      code
        images
        javaFile1
        test

images is directory with many images.

Now the code for test looks like this:

    public void doSome(){
        System.out.println(this.getClass().getResource("./images/image1.png"));
    }
    public static void main(String[] args){
        test test = new test();
        test.doSome();
    }

I get the file as file:

--location-- /main-directory/out/production/main-directory/code/images/image1.png

But when I run this.getClass().getResource("./images/image1.png") in javaFile1, it returns null. I am not able to understand that why does javaFile1 not find the resource while test does even though they are in the same directory. I tried some answers from SO, but none of them worked.

I would appreciate any help.


Solution

  • For some reason it fixed when I added "/code/images/image1.png" instead of "./images/image1.png". It might be that resources need the parent directory to find it.