0

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
  }
}
Community
  • 1
  • 1
EDOLLing
  • 5
  • 4
  • It's not a trivial task, but refer to the linked question for solutions. – Tunaki Oct 27 '16 at 19:29
  • @Tunaki thanks for the link, but many of the solutions rely on some form of classLoader.getResourceStream(resource) to read the directory contents which still returns nothing for me. If I do getResourceStream("dir/fileA") everything is file, if I do getResourceStream("dir/") I get nothing. I'm not sure why... if it's due to something super obvious or not but if you have any ideas I'm open to it! – EDOLLing Oct 27 '16 at 20:13
  • That sounds like a different problem. But I'd use `getClass().getResourceAsStream(...)`, see also http://stackoverflow.com/questions/6608795/what-is-the-difference-between-class-getresource-and-classloader-getresource – Tunaki Oct 27 '16 at 20:33

0 Answers0