日期:2014-05-19 浏览次数:20677 次
String pack = "com.test"; pack ="/"+pack.replace(".", "/"); String packPath = System.getProperty("user.dir")+ "/src"+ pack;
------解决方案--------------------
参考代码,jar 的部分没处理好,你自己完善一下吧。
import java.io.File; import java.io.IOException; import java.net.JarURLConnection; import java.net.URISyntaxException; import java.net.URL; import java.net.URLConnection; import java.util.Enumeration; import java.util.jar.JarEntry; public class Main { public static void main(String[] args) throws IOException, URISyntaxException, ClassNotFoundException { ClassLoader classloader = Thread.currentThread().getContextClassLoader(); String baseName = baseName(classloader); Enumeration<URL> em = classloader.getResources("com/test"); while(em.hasMoreElements()) { URL url = em.nextElement(); // jar 包中的 URLConnection connection = url.openConnection(); if("jar".equals(url.getProtocol()) && connection instanceof JarURLConnection) { JarURLConnection jar = (JarURLConnection)connection; JarEntry entry = jar.getJarEntry(); System.out.println(entry); for(Enumeration<JarEntry> e = jar.getJarFile().entries(); e.hasMoreElements(); ) { System.out.println(e.nextElement()); } continue; } // 源代码中的 File file = new File(url.toURI()); File[] files = file.listFiles(); for(File f : files) { scan(f, baseName, classloader); } } } private static String baseName(ClassLoader classloader) throws URISyntaxException { return new File(classloader.getResource("").toURI()).getAbsolutePath(); } private static void scan(File dir, String baseName, ClassLoader classloader) throws ClassNotFoundException { if(dir.isDirectory()) { File[] files = dir.listFiles(); for(File file : files) { scan(file, baseName, classloader); } return; } scan2(dir, baseName, classloader); } private static void scan2(File dir, String baseName, ClassLoader classloader) throws ClassNotFoundException { String className = dir.getAbsolutePath().substring(baseName.length() + 1); int dot = className.indexOf('.'); if(dot > -1) { className = className.substring(0, dot); } if(className.indexOf('\\') > -1) { className = className.replace('\\', '.'); } if(className.indexOf('/') > -1) { className = className.replace('/', '.'); } Class<?> clazz = classloader.loadClass(className); System.out.println(clazz.getName()); } protected static String determineRootDir(String location) { int prefixEnd = location.indexOf(":") + 1;