递归查找文件 -------陈开源

程序代码如下:
import java.io.*;
import java.util.jar.*;
import java.util.Enumeration;

/**
* <p>Title: SearchClass</p>
*
* <p>Descriptionc:查找指定目录下的class文件 </p>
* @version 1.0
*/
public class SearchClass {
static String className = "";
static int result = 0;
static boolean flag = false;

/**
* visit
*
* @param f File
* @throws Exception
* @todo 访问文件,并比较是否为要查找的class文件
*/
public static void visit(File f) throws Exception {
if (! (f.isDirectory())) {
String fileName = f.getName();
//f为jar文件
if (fileName.lastIndexOf(".jar") > 0) {
try {
JarFile jarFile = new JarFile(f);
JarEntry jarEntry = jarFile.getJarEntry(className);
if (jarEntry != null) {
result++;
System.out.println(result + ":在jar文件" + f + "中找到");
}
Enumeration e = jarFile.entries();
while (e.hasMoreElements()) {
String inname = e.nextElement().toString();
int j = inname.lastIndexOf("/");
if (j > 0) {
String suffix = inname.substring(j + 1, inname.length());
if (suffix.equals(className))
flag = true;
}
if (flag) {
result++;
System.out.println(result + ":在jar文件:" + f + "中找到");
System.out.println(inname);
flag = false;
break;
}
}

}
catch (Exception e) {
e.printStackTrace();
}
}
//f为class文件
else if (fileName.lastIndexOf(".class") > 0) {
if (fileName.equals(className)) {
result++;
System.out.println(result + ":在class文件" + f + "中找到");
}
}

}
else {
throw new Exception("发生意外!");
}

}

/**
* walk
*
* @param f File
* @todo 递归目录
*/
public static void walk(File f) {
//如果当前File是个文件,调用visit();
if (f.isFile())
try {
visit(f);
}
catch (Exception e) {
e.printStackTrace();
}
//如果当前File是个目录,存储其子目录,并递归调用walk();
else if (f.isDirectory()) {
String list[] = f.list();
for (int i = 0; i < list.length; i++)
walk(new File(f, list[i]));
}
}

/**
* main
*
* @param args String[]
* @todo 主函数
*/
public static void main(String args[]) {
if (args.length > 1) {
className = args[1] + ".class";
try {
File srcDirectory = new File(args[0]);
File firstList[] = srcDirectory.listFiles();
for (int i = 0; i < firstList.length; i++) {
if (firstList[i].exists()) {
walk(firstList[i]);
}
else
System.err.println("不能读取目录: " + srcDirectory);
}
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println("搜索结果:共出现" + result + "处");
}
catch (Exception e) {
e.printStackTrace();
}
}
else {
System.out.println("输入格式有误!");
System.out.println("正确输入格式:java SearchClass 搜索目录 类名称");
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值