0

I am testing(JUnit) a logic within a class residing somewhere under the main directory.
In that logic, I am trying to get the path of "dir3" by doing something like

this.getClass().getClassLoader().getResource("dir1/dir2/dir3").getPath()

but, the loader can not seem to find it.

When I rewrite the code to

this.getClass().getClassLoader().getResource("dir1/dir2").getPath()

it works.

Can't I have the loader find the correct directly path(dir3)?


Directory streucture(Maven)

src
 |-main
 |   |-resources
 |        |-dir1
 |           |-dir2
 |              |-dir3
 |-test
     |-resources(empty)
Kevin Hooke
  • 2,583
  • 2
  • 19
  • 33
d-_-b
  • 4,142
  • 6
  • 28
  • 43
  • Why do you need a file path? Assuming that classpath resources are loaded from actual files is frail. – Thilo Mar 10 '17 at 06:58
  • 2
    FWIW from your picture, the only difference I can see between "dir2" and "dir3" is that "dir3" is empty (and may therefore not have been included in the build result). Try if putting a dummy file in there helps. – Thilo Mar 10 '17 at 07:01
  • Could you elaborate on "Assuming that classpath resources are loaded from actual files is frail"? – d-_-b Mar 10 '17 at 07:21
  • Please refer [Similar issue](http://stackoverflow.com/questions/2593154/get-a-resource-using-getresource#answer-2593175). Hope this resolves your issue. – Chandni Mar 10 '17 at 07:32
  • @d.s If the classpath includes jar files (and that is very common), many resources are loaded from inside these archives. There is no separate file for these resources. – Thilo Mar 10 '17 at 11:24
  • @Thilo Those directories(and some files underneath) are placed under the resource directory for some specific purposes. How do these have something to do with other resources loaded from jar files? I do not still get your point... – d-_-b Mar 10 '17 at 17:23
  • All I am saying is that if the project was built for example as an executable jar, these files won't be there. And if you are loading resources from the classpath, you can usually do that by getting them through the classloader (instead of from the filesystem via a path). That has side-benefits as well, for example to allow the user to override the resource by augmenting the classpath setting. So unless you really need actual files (for example to list stuff in a directory, or to write to them), try to use `getResource().getInputStream()` to load data. – Thilo Mar 11 '17 at 00:49

1 Answers1

0

@Thilo
Thank you. The directly was indeed excluded. Putting some file in it has made this work.

d-_-b
  • 4,142
  • 6
  • 28
  • 43