利用多线程
通过模糊查询查找计算机磁盘的文件
例如:查找这个文件:ojdbc5dms_g.jar
查找结果:
主要代码如下:
1 import java.io.File; 2 import java.util.Date; 3 4 public class FileFind extends Thread { 5 6 private String path; 7 private String name; 8 private int relust; 9 10 public FileFind(String path, String name) { 11 super(); 12 this.path = path; 13 this.name = name; 14 } 15 16 public FileFind() { 17 super(); 18 // TODO Auto-generated constructor stub 19 } 20 21 public FileFind(String path, String name, int relust) { 22 super(); 23 this.path = path; 24 this.name = name; 25 this.relust = relust; 26 } 27 28 @Override 29 public void run() { 30 31 filePath(path, name); 32 System.out.println(path+"中查找到"+relust+"个文件"); 33 System.out.println(path+"查找结束"); 34 System.out.println(path+"查找结束时间"+new Date()); 35 } 36 37 public void filePath(String listRoots, String name) { 38 39 File file = new File(listRoots); 40 File[] listFiles = file.listFiles(); 41 if (listFiles != null) { 42 for (File listFile : listFiles) { 43 if (!listFile.isHidden()) { 44 if (listFile.isDirectory()) { 45 if (listFile.getName().matches(".*" + name + ".*")) { 46 System.out.println(listFile.getAbsolutePath()); 47 relust++; 48 } 49 filePath(listFile.getAbsolutePath(), name); 50 } else { 51 if (listFile.getName().matches(".*" + name + ".*")) { 52 53 System.out.println(listFile.getAbsolutePath()); 54 relust++; 55 } 56 57 } 58 59 } 60 61 } 62 } 63 64 } 65 66 }
上面这个的是继承了线程类Thread,重写run方法。
启动线程代码:
1 import java.io.File; 2 import java.util.Date; 3 4 public class FileFindTest { 5 public static void main(String[] args) { 6 find("ojdbc5dms_g.jar"); 7 8 } 9 10 public static void find(String fileName) { 11 System.out.println("开始查找"+new Date()); 12 File[] listRoots = File.listRoots(); 13 int result = 0; 14 for (File listRoot : listRoots) { 15 FileFind fileFind = new FileFind(listRoot.getAbsolutePath(), fileName, result); 16 fileFind.start(); 17 System.out.println(fileFind.getName() + "开始运行"); 18 19 } 20 } 21 }
很简单。就是多线程查询系统文件的一个demo!