I am writing a Java Maven plugin in Eclipse, and inside it I want to access some files from src/main/resources
. Since the number of files and actual filenames should be unknown to the plugin, I plan on storing the files inside some directory that the plugin will know of the name of. So for example, given the file structure:
src/main/resources
src/main/resources/dir
src/main/resources/dir/fileA
src/main/resources/dir/fileB
The plugin will want to access fileA
and fileB
, but won't know their names. The plugin will however know the files it wants to access are in the directory dir
. My question is that I want to know how to properly access dir
from src/main/resources
in a way where I can easily parse it's contents while the plugin is running.
I have found many similar questions/tutorials online, but most of them address accessing a file that is not a directory (or maybe I just didn't search well enough). For example I found the suggestion to use classLoader.getResourceStream(resource)
from the question Read file from /src/main/resources/ to be useful for file reading. However, when the resource is a directory, reading from the stream returns nothing.
Right now I am doing the following to 1. get the location of the desired directory (basically the JAR) and 2. access the directory's contents, but I want to know if there is a better way since it feels messy:
// Get location of desired directory - basically the code's JAR file
ClassLoader classLoader = getClass().getClassLoader();
String jarLocation = classLoader.getResource("dir").getFile();
jarLocation = jarLocation.replace("file:","").replace("!/dir","");
JarFile jarFile = new JarFile(new File(jarLocation));
// Parse Jar for desired directory content
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
if (entry.getName.contains("dir/") && !entry.isDirectory()) {
// Process entry file in some way
}
}