package com.frame.lss.file;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* 文件搜索
* @author SHOUSHEN LUAN
*/
public class FileSearch {
public static final String PATH = "D://Software";
public static void main(String arg[]) {
try {
searchFile(PATH, "Session.js");
} catch (Exception e) {
}
}
public static boolean isSearchFile(String searchFile, String filePath) {
int lastFileIndex = filePath.lastIndexOf("//");
if (filePath.substring(lastFileIndex + 1).equalsIgnoreCase(searchFile)) {
return true;
}
return false;
}
/**
* 实现文件搜索功能
*
* @author SHOUSHEN LUAN
* @param path
* @param fileName
* @throws Exception
*/
public static void searchFile(String path, String fileName)
throws Exception {
File file = new File(path);
if (!file.exists()) {
throw new Exception("指定路径不存在:" + file.getPath());
} else {
String[] files = file.list();
List isDirectory = new ArrayList();
while (true) {
for (int i = 0; i < files.length; i++) {
String pathB = path + "//" + files[i];
File f = new File(pathB);
if (f.isFile()) {
if (isSearchFile(fileName, f.getPath())) {
System.out.println("查询结果:" + f.getPath());
}
} else if (f.isDirectory()) {
isDirectory.add(f.getAbsolutePath());
}
}
while (isDirectory.size() > 0) {
List list = new ArrayList();
for (int i = 0; i < isDirectory.size(); i++) {
String pathC = isDirectory.get(i);
File fil = new File(pathC);
String[] flist = fil.list();
for (int j = 0; j < flist.length; j++) {
String pathD = pathC;
pathD = pathD + "//" + flist[j];
File ff = new File(pathD);
if (ff.isFile()) {
if (isSearchFile(fileName, ff.getPath())) {
System.out.println("查询结果:" + ff.getPath());
}
} else if (ff.isDirectory()) {
list.add(ff.getAbsolutePath());
}
}
} isDirectory = list; } break; } } }}