Here you can find the source of getResourceListing(Class> clazz, String path)
Parameter | Description |
---|---|
clazz | Any java class that lives in the same place as the resources you want. |
path | Should end with "/", but not start with one. |
Parameter | Description |
---|---|
URISyntaxException | an exception |
IOException | an exception |
public static String[] getResourceListing(Class<?> clazz, String path) throws URISyntaxException, IOException
//package com.java2s; /**//from w w w. j a v a 2s.com * This work is licensed under a Creative Commons Attribution-NoDerivatives 4.0 * International License. http://creativecommons.org/licenses/by-nd/4.0/ * * @author Wruczek */ import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; import java.net.URLDecoder; import java.util.Enumeration; import java.util.HashSet; import java.util.Set; import java.util.jar.JarEntry; import java.util.jar.JarFile; public class Main { /** * List directory contents for a resource folder. Not recursive. This is * basically a brute-force implementation. * * @author Greg Briggs * @param clazz * Any java class that lives in the same place as the resources * you want. * @param path * Should end with "/", but not start with one. * @return Just the name of each member item, not the full paths. * @throws URISyntaxException * @throws IOException */ public static String[] getResourceListing(Class<?> clazz, String path) throws URISyntaxException, IOException { URL dirURL = clazz.getClassLoader().getResource(path); if (dirURL == null) { String me = clazz.getName().replace(".", "/") + ".class"; dirURL = clazz.getClassLoader().getResource(me); } if (dirURL.getProtocol().equals("jar")) { String jarPath = dirURL.getPath().substring(5, dirURL.getPath().indexOf("!")); JarFile jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8")); Enumeration<JarEntry> entries = jar.entries(); Set<String> result = new HashSet<String>(); while (entries.hasMoreElements()) { String name = entries.nextElement().getName(); if (name.startsWith(path)) { String entry = name.substring(path.length()); int checkSubdir = entry.indexOf("/"); if (checkSubdir >= 0) { entry = entry.substring(0, checkSubdir); } result.add(entry); } } jar.close(); return result.toArray(new String[result.size()]); } throw new UnsupportedOperationException("Cannot list files for URL " + dirURL); } }