java 扫描文件_java扫描文件。

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 classScanUtil {//定义一个set来保存完整类名

private static Set classNames = new HashSet();public static Setscan(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 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);

}returnclassNames;

}/**

* 从项目文件获取某包下所有类

* @param filePath 文件目录

* @param packageName 包名*/

private static voidscanFromDir(String filePath,String packageName){

File[] files= newFile(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 voidmain(String[] args) {

Set classNames=scan("edu.nf");for(String path:classNames){

System.out.println(path);

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值