18

Lets assume my classes are loaded from a compressed .war file or loaded elsewhere, how can I discover all the resources in a given package? Enumerating files will not really work, since this is a war file. Most likely this will involve using the current classloader?

Is there a library out there that does something like that? Googling revealed only some hacks with listing files.

Adam Bellaire
  • 108,003
  • 19
  • 148
  • 163
Andreas Petersson
  • 16,248
  • 11
  • 59
  • 91

4 Answers4

22

Yes. You can use ClassLoader.getResources("");

Or you could use ferret API:
https://www.ohloh.net/p/pureperfect-ferret

This API allows you to scan the class path as well as arbitrary archives and directories using the Visitor pattern.

jcfolsom
  • 113
  • 2
  • 8
  • +1 Correct solution, should work for any classloader and in web containers – Aaron Digulla May 02 '13 at 11:56
  • I believe `ClassLoader.getResources("")` doesn't really work for jars. Please see the comments on [this question](http://stackoverflow.com/questions/21836950/urlclassloader-getresources-empty-resource-name-not-giving-roots-of-jars). Also Spring `PathMatchingResourcePatternResolver` mentions in [their documentation](http://docs.spring.io/spring-framework/docs/2.5.x/api/org/springframework/core/io/support/PathMatchingResourcePatternResolver.html) the tricks they implemented to actually find resources from a JAR (see "Implications on portability" section). – pazabo Mar 26 '15 at 06:33
  • yes it works for jars. It works for any environment. – jcfolsom Jan 15 '16 at 23:15
7

No, you can't list resources in a package because the JVM simply doesn't know what resources are in what package. See this question.

Community
  • 1
  • 1
SCdF
  • 57,260
  • 24
  • 77
  • 113
6

The Spring Framework offers a class called PathMatchingResourcePatternResolver. With this class you can give Ant style paths with wildcards and it will find the relevant resources for you (searching through the folders and jars on the classpath).

Daniel Rikowski
  • 71,375
  • 57
  • 251
  • 329
DerHeiligste
  • 11
  • 1
  • 1
3

I do this: - before packaging, ls myResources/*.ext > myResources/list.txt - then just read the file first

Vlad Patryshev
  • 1,379
  • 1
  • 10
  • 16