ResourceUtil { public static List<String> list(Class<?> clazz, String path, FilenameFilter filter) throws URISyntaxException, IOException { URL dirUrl = clazz.getResource(path); if (dirUrl != null && dirUrl.getProtocol().equals("file")) { return Arrays.asList(new File(dirUrl.toURI()).list(filter)); } if (dirUrl == null) { String className = clazz.getName().replace(".", "/") + ".class"; dirUrl = clazz.getClassLoader().getResource(className); } if (dirUrl.getProtocol().equals("jar")) { if (path.startsWith("/")) { path = path.substring(1); } if (!path.endsWith("/")) { path = path + "/"; } String jarPath = dirUrl.getPath().substring(5, dirUrl.getPath().indexOf("!")); JarFile jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8")); Set<String> fileSet = new HashSet<String>(); try { Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { String entryName = entries.nextElement().getName(); if (!entryName.startsWith(path)) { continue; } String name = entryName.substring(path.length()); if (!"".equals(name)) { int checkSubdir = name.indexOf("/"); if (checkSubdir >= 0) { name = name.substring(0, checkSubdir); } if (filter == null || filter.accept(null, name)) { fileSet.add(name); } } } } finally { jar.close(); } return Lists.newArrayList(fileSet); } throw new UnsupportedOperationException(MessageFormat.format("Cannot list files for URL {0}", dirUrl)); }  static List<String> list(Class<?> clazz, String path, FilenameFilter filter); static List<String> list(Class<?> clazz, String path);  }
@Test public void listFilesTest() throws Exception { List<String> fileList = ResourceUtil.list(Test.class, "/junit/framework"); Assert.assertTrue(fileList.contains("Test.class")); fileList = ResourceUtil.list(Test.class, "/junit/framework/"); Assert.assertTrue(fileList.contains("Test.class")); fileList = ResourceUtil.list(Test.class, "junit/framework/"); Assert.assertTrue(fileList.contains("Test.class")); fileList = ResourceUtil.list(Test.class, "junit/framework/"); Assert.assertTrue(fileList.contains("Test.class")); }