this.getClass().getClassLoader().getResource("...") and NullPointerException

Viewed 199747

I have created a minimal maven project with a single child module in eclipse helios.

In the src/test/resources folder I have put a single file "install.xml". In the folder src/test/java I have created a single package with a single class that does:

  @Test
  public void doit() throws Exception {
    URL url = this.getClass().getClassLoader().getResource("install.xml");
    System.out.println(url.getPath());

  }

but when I run the code as a junit 4 unit test I just get a NullPointerException. This has worked fine a million of times before. Any ideas?

I have followed this guide:

http://www.fuyun.org/2009/11/how-to-read-input-files-in-maven-junit/

but still get the same error.

9 Answers

If you are using a Java Maven project in Netbeans (not Ant), then place your file as following:

src
  test
    java
    resources
      install.xml

Notice the location of the resources folder. You can also have nested folders within the resources. Then you can access your file as following,

URL url = this.getClass().getResource("/install.xml");

More details: https://stackoverflow.com/a/56008648/1942069

Related