Question

In one of my JUnit tests, I am trying to load all the files contained in a directory. I used .getClassLoader().getResource("otherresources") to find the directory. I then made a new java.io.File. I then used listFiles() to get all the children files and then used .getClassLoader().getResource() again to load each of those files.

URL url = FileLoadTest.class.getClassLoader().getResource("otherresources");
File directory = new File(url.getPath());
File[] files = directory.listFiles();

Basically, I want to be able to load all the files in a directory without knowing exactly what they are.

I can properly run the test in Eclipse. When I go to build the project with Maven (mvn install) or run the test case by itself using surefire (mvn -Dtest=FileTest test) the test case fails with a NullPointerException. I think the issue has something to do with the File api not working as intended within the JAR file that the resources are deployed to.

Any tips on how to fix this?

Was it helpful?

Solution

Correct, the File API can only read from the file system, and not within JAR files.

Unfortunately, there's not a good way to do exactly what you're trying to do, without using some additional libraries that utilize some hacks in an attempt to accomplish just this. Resources on the classpath are not meant to be enumerable, as there is no guarantee where they are loaded from (could be from disk, in a JAR file, HTTP, a database, or other exotic resources - including ones where the enumeration of available files would not be feasible). The best approach is to include an "index" or other similar file with a well-known name, which can be referenced to find other resources you're interested in.

One of these "hacks" would be, if you know the path to the JAR file(s), you could read from them using JarFile (or even just ZipFile).

OTHER TIPS

.getClassLoader().getResource("otherresources")

Untested. Once you have the 'directory', use it to get back to the archive itself.

  • Establish a ZipInputStream to the archive.
  • Call getNextEntry() until null and add the entries matching the required location to an expandable list (e.g. ArrayList).
  • Construct an URL from the location of the archive and ZipEntry.getName()

Of course, I would normally suggest creating a list of the target resources when making the archive, then including that list at a known location in the archive. But the above might suffice for this use case.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top