Skip to content

Instantly share code, notes, and snippets.

@marko-asplund
Created October 14, 2015 12:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marko-asplund/58f91f386c363e89fd3d to your computer and use it in GitHub Desktop.
Save marko-asplund/58f91f386c363e89fd3d to your computer and use it in GitHub Desktop.
package fi.markoa.proto.libload;
import java.io.File;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
public class ResourceCataloguer {
private enum Protocol { JAR, FILE }
public List<String> listResourceDirectory(String dir) {
URL u = this.getClass().getResource("/"+dir);
Protocol protocol = Protocol.valueOf(u.getProtocol().toUpperCase());
List<String> res = new ArrayList<String>();
switch (protocol) {
case JAR:
try {
JarURLConnection juc = (JarURLConnection)u.openConnection();
for (Enumeration<JarEntry> en = juc.getJarFile().entries(); en.hasMoreElements(); ) {
JarEntry je = en.nextElement();
if(!je.isDirectory() && je.getName().startsWith(dir+"/")) {
res.add("/"+je.getName());
}
}
} catch (IOException ex) {
throw new RuntimeException("failed to open jar file: "+u, ex);
}
break;
case FILE:
for(File f : (new File(u.getFile())).listFiles()) { // only top-level directory
res.add(String.format("/%s/%s", dir, f.getName()));
}
break;
default:
throw new RuntimeException(String.format("unsupported protocol: %s, %s", protocol, u));
}
return res;
}
public static void main(String ... args) throws Exception {
ResourceCataloguer m = new ResourceCataloguer();
for(String f : m.listResourceDirectory("lib")) {
System.out.println("res: "+f+", "+m.getClass().getResource(f));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment