@文件查找工具。开发使用的文件查找工具因为需要与Windows进行界面交互,因此需要的时间会较长。自己写一个查找代码,可以很快的找到需要查找的文件和信息,并在控制台展示。
简易写法
public static List<String> FileSearch(String filePath, String fileType, String passType) throws IOException {
List<String> result = Collections.synchronizedList(new ArrayList<>());
File file = new File(filePath);
System.out.println(filePath);
if (!file.exists() || file.getName().contains(passType)) {
return result;
}
if (file.isFile()) {
if (file.getName().contains(fileType)) {
result.add(file.getCanonicalPath());
}
} else {
for (String childPath:file.list()) {
String esPath = filePath + "\\" + childPath;
result.addAll(FileSearch(esPath, fileType, passType));
}
}
return result;
}
可以不添加返回值,直接使用System.out.print在控制台输出。
子文件夹过多
public static void FileSearch(String filePath, String fileType, String passType, List<String> result) throws IOException {
File file = new File(filePath);
if (!file.exists() || file.getName().contains(passType)) {
return;
}
if (file.isFile()) {
if (file.getName().contains(fileType)) {
System.out.println(file.getCanonicalPath());
result.add(file.getCanonicalPath());
}
} else {
String[] childList = file.list();
ExecutorService es = new ThreadPoolExecutor(15, Integer.MAX_VALUE,
5L, TimeUnit.MINUTES, new ArrayBlockingQueue<Runnable>(100));
for (String childPath:childList) {
String esPath = filePath + "\\" + childPath;
es.execute(new Runnable() {
@Override
public void run() {
try {
FileSearch(esPath, fileType, passType, result);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
try {
es.shutdown();
if (!es.isShutdown()) {
es.awaitTermination(5, TimeUnit.MINUTES);
}
} catch (InterruptedException e) {
try {
es.shutdownNow();
if (!es.isShutdown()) {
es.awaitTermination(5, TimeUnit.MINUTES);
}
} catch (InterruptedException ex) {
es.shutdownNow();
}
}
}
}
使用多线程的时候,如果在mian方法中直接打印,可能子线程未完成而得不到结果。建议直接打印到控制台,如果必须将结果回传至调用者,需要将主线程等待一段时间(也可以监控子线程全部完成后再打印)。
python的简单查找
import os
def search_file_by_name(file_path, file_name):
file_list = os.listdir(file_path)
for file in file_list:
full_file = file_path + "\\" + file
if os.path.exists(full_file) and os.path.isfile(full_file):
if str.__contains__(full_file, file_name):
print(full_file)
else:
search_file_by_name(full_file, file_name)
return
def check_file(file_path, file_name, file_pass = []):
file_list = os.listdir(file_path)
for file in file_list:
full_file = file_path + "\\" + file
for pass_file in file_pass:
if str.__contains__(full_file, pass_file):
continue
if os.path.exists(full_file) and os.path.isfile(full_file):
if str.__contains__(full_file, file_name):
print(full_file)
else:
search_file_by_name(full_file, file_name)
return