16-案例实现
案例实现
根据以下步骤完成本案例。
1.创建一个名为 FileSearch
的类,并实现 Runnable
接口:
public class FileSearch implements Runnable {
2.声明两个私有属性——一个用来存储要搜索的文件名,另一个用来存储要搜索的初始路径。在该类构造器中初始化这两个属性:
private String initPath;
private String fileName;
public FileSearch(String initPath, String fileName) {
this.initPath = initPath;
this.fileName = fileName;
}
3.实现 FileSearch
类的 run()
方法。首先检测 initPath
是否为一个文件夹,如果是,则调用 directoryProcess()
方法。该方法会抛出 InterruptedException
异常,因此需要捕获处理:
@Override
public void run() {
File file = new File(initPath);
if (file.isDirectory()) {
try {
directoryProcess(file);
} catch (InterruptedException e) {
System.out.printf("%s: The search has been interrupted",
Thread.currentThread().getName());
}
}
}
4.实现 directoryProcess()
方法。这个方法会获取指定文件夹中的文件及其子文件夹,然后处理它们。对于每个子文件夹,该方法会以其作为参数递归调用自己;对于每个文件,该方法将调用 fileProcess()
方法进行处理。在处理完这些文件和子文件夹以后,该方法将判断线程是否被中断。在本案例中,如果线程被中断,则会抛出 InterruptedException
异常:
private void directoryProcess(File file) throws InterruptedException {
File list[] = file.listFiles();
if (list != null) {
for (int i = 0; i < list.length; i++) {
if (list[i].isDirectory()) {
directoryProcess(list[i]);
} else {
fileProcess(list[i]);
}
}
if (Thread.interrupted()) {
throw new InterruptedException();
}
}
5.实现 fileProcess()
方法。该方法将对比文件名是否与所要搜索的文件名相同,如果相同,则向控制台输出信息。完成对比后,该方法会判断线程是否已被中断,在本案例中,如果发生线程中断,则抛出 InterruptedException
异常:
private void fileProcess(File file) throws
InterruptedException {
if (file.getName().equals(fileName)) {
System.out.printf("%s : %s\n",
Thread.currentThread().getName(),
file.getAbsolutePath());
}
if (Thread.interrupted()) {
throw new InterruptedException();
}
}
6.现在,可以开始实现应用程序的入口,创建包含 main()
方法的 Main
类:
public class Main {
public static void main(String[] args) {
7.创建并初始化一个 FileSearch
对象,然后用 Thread
对象启动线程来执行该任务。本案例采用的是Windows路径。在其他操作系统(如Linux或者iOS)下,需要将路径修改为对应系统上一个存在的文件的路径:
FileSearch searcher = new FileSearch("C:\\Windows",
"explorer.exe");
Thread thread=new Thread(searcher);
thread.start();
8.等待10s后中断线程:
try {
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
thread.interrupt();
}
9.运行案例并查看结果。