前言:一步一步来实现迷你ioc框架,前面的容器工厂也是一个铺垫,这次的扫描文件也是一个铺垫……
需求:扫描当前项目下所有文件。包括文件夹下文件夹里面的文件。利用递归进行扫描
ScanFileUtil类
package edu.nf.beans.util; import java.io.File; import java.io.IOException; import java.net.JarURLConnection; import java.net.URL; import java.net.URLDecoder; import java.util.Enumeration; import java.util.HashSet; import java.util.Set; /** * Created by Administrator on 2017/12/12. */ public class ScanUtil { //定义一个set来保存完整类名 private static Set<String> classNames = new HashSet<String>(); public static Set<String> scan(String packageName) { if(packageName==null){//抛异常 throw new RuntimeException("The path can not be null."); } //传入的包名格式为 edu.nf 进行转换 String packagePath = packageName.replace(".","\"); //根据当前线程当前执行类获取url ClassLoader loader = Thread.currentThread().getContextClassLoader(); try { //枚举获得一个路径 Enumeration<URL> urls = loader.getResources(packagePath); while (urls.hasMoreElements()){//如果不为空 URL url = urls.nextElement();//获取路径 System.out.println(url+"111"); if("file".equals(url.getProtocol())){//如果是文件 String path = URLDecoder.decode(url.getPath(),"utf-8");//处理中文乱码 scanFromDir(path,packageName);//进行类扫描,保存Set集合 } if("jar".equals(url.getProtocol())){//如果是jar JarURLConnection connection = (JarURLConnection)url.openConnection(); String pathjar = URLDecoder.decode(String.valueOf(connection),"utf-8"); scanFromDir(pathjar,packageName); } } } catch (IOException e) { throw new RuntimeException("Resolve path error.", e); } return classNames; } /** * 从项目文件获取某包下所有类 * @param filePath 文件目录 * @param packageName 包名 */ private static void scanFromDir(String filePath,String packageName){ File[] files = new File(filePath).listFiles(); packageName = packageName + "."; for (File childFile:files){ //遍历文件 if(childFile.isDirectory()){//还是文件夹就继续递归 scanFromDir(childFile.getPath(),packageName+childFile.getName()); }else{ String fileName = childFile.getName();//文件名 if(fileName.endsWith(".class")){//判断文件名是否是.class结尾 if(packageName.charAt(0)=='.'){//判断开头是否有'.',有的话截取 packageName = packageName.substring(1,packageName.length()); } //拼接字符串,得到完整类名 如:edu.nf.beans.util.ScanUtil String className = packageName+fileName.replace(".class",""); classNames.add(className); } } } } public static void main(String[] args) { Set<String> classNames=scan("edu.nf"); for(String path:classNames){ System.out.println(path); } } }
扫描文件,有许多种方式,但是都离不开递归