Carlos Goce
Carlos Goce

Reputation: 1665

Not able to load a resource from the resources test folder

I'm trying with this simple test:

@Test
public void testResourceExist() {
    URL file = getClass().getResource("sample.htm");

    Assert.assertNotNull(file);
}

My directory structure is:

src
  - main
      - java
      - resources
  - test
      - java
          ResourcesTest.java
      - resources
          sample.htm

I'm using IntelliJ Idea and maven and even the Ide autocompletes the sample.htm file. If i check the test-classes folder i can see the sample.htm file there.

Upvotes: 0

Views: 109

Answers (2)

Software Engineer
Software Engineer

Reputation: 16140

Actually, you shouldn't be reading this as a file resource, but as a classpath resource. All files in resources are packaged as part of your jar, not placed directly on the filesystem, and all class paths are absolute, so you don't need a slash at the start. Rather, the error you have here is that you're trying to read a file resource, using getResource(), rather than a classpath resource, using getClasspathResourceAsStream() or something similar. If you use the latter then you'll not need the slash.

Upvotes: 1

Carlos Goce
Carlos Goce

Reputation: 1665

I just needed to add a slash before the resource name.

"/sample.htm" instead of "sample.htm" and its working

Upvotes: 1

Related Questions