1 package com.ochafik.net; 2 3 import java.io.File; 4 import java.io.IOException; 5 import java.io.InputStream; 6 import java.net.URL; 7 import java.util.ArrayList; 8 import java.util.List; 9 import java.util.jar.JarEntry; 10 import java.util.jar.JarInputStream; 11 12 import com.ochafik.util.listenable.Filter; 13 14 public class URLUtils { 15 16 public static URL getResource(Class<?> cl, String path) throws IOException { 17 String clp = cl.getName().replace('.', '/') + ".class"; 18 URL clu = cl.getClassLoader().getResource(clp); 19 String s = clu.toString(); 20 if (s.endsWith(clp)) 21 return new URL(s.substring(0, s.length() - clp.length()) + path); 22 23 if (s.startsWith("jar:")) { 24 String[] ss = s.split("!"); 25 return new URL(ss[1] + "!/" + path); 26 } 27 return null; 28 } 29 30 public static List<URL> listFiles(URL directory, Filter<String> pathAccepter) throws IOException { 31 List<URL> ret = new ArrayList<URL>(); 32 String s = directory.toString(); 33 if (s.startsWith("jar:")) { 34 String[] ss = s.substring("jar:".length()).split("!"); 35 String path = ss[1]; 36 URL target = new URL(ss[0]); 37 InputStream tin = target.openStream(); 38 try { 39 JarInputStream jin = new JarInputStream(tin); 40 JarEntry je; 41 while ((je = jin.getNextJarEntry()) != null) { 42 String p = "/" + je.getName(); 43 if (p.startsWith(path) && p.indexOf('/', path.length() + 1) < 0) 44 if (pathAccepter == null || pathAccepter.accept(path)) 45 ret.add(new URL("jar:" + target + "!" + p)); 46 } 47 } finally { 48 tin.close(); 49 } 50 } else if (s.startsWith("file:")) { 51 File f = new File(directory.getFile()); 52 File[] ffs = f.listFiles(); 53 if (ffs != null) 54 for (File ff : ffs) 55 if (pathAccepter == null || pathAccepter.accept(ff.toString())) 56 ret.add(ff.toURI().toURL()); 57 } else 58 throw new IOException("Cannot list contents of " + directory); 59 60 return ret; 61 } 62 }