标签:== -- break com public generate Stub trace nbsp
目标:根据给出的目录地址,要求查找目录下所有指定后缀名suffix的文件,若包含指定字符串,则打印该文件地址。
1 package multiplethread; 2 3 import java.io.BufferedReader; 4 import java.io.File; 5 import java.io.FileReader; 6 import java.io.IOException; 7 import java.util.concurrent.LinkedBlockingQueue; 8 import java.util.concurrent.ThreadPoolExecutor; 9 import java.util.concurrent.TimeUnit; 10 11 public class TestMultithread { 12 public static void main(String[] args) { 13 String path = "F:\\project\\javastudy"; 14 String suffix = ".java"; 15 usingThreadPool utp = new usingThreadPool(); 16 utp.search(path, "Magic", suffix); 17 } 18 19 static class usingThreadPool { 20 ThreadPoolExecutor threadPool = new ThreadPoolExecutor(10, 15, 60, TimeUnit.SECONDS, 21 new LinkedBlockingQueue<>()); 22 23 // 使用多线程进行文件内容搜索 24 public void runThreadPool(File x, String content) { 25 threadPool.execute(new Runnable() { 26 // 每个具体线程要干的事:查找某个文件内容是否含有content字符串 27 @Override 28 public void run() { 29 // TODO Auto-generated method stub 30 try (BufferedReader br = new BufferedReader(new FileReader(x));) { 31 while (true) { 32 String line = br.readLine(); 33 if (line == null) 34 break; 35 if (line.contains(content)) { 36 System.out.printf("找到目标字符串 %s ,在文件%s%n", content, x.getAbsoluteFile()); 37 break; // 只要文件含有content,不管出现多少次,只打印一次文件地址 38 } 39 } 40 } catch (IOException e) { 41 // TODO Auto-generated catch block 42 e.printStackTrace(); 43 } 44 } 45 }); 46 } 47 48 public void search(String path, String content, String suffix) { 49 File f = new File(path); 50 File[] fs = f.listFiles(); 51 for (File x : fs) { 52 if (x.isDirectory()) 53 search(x.getAbsolutePath(), content, suffix); 54 else if (x.isFile() && x.getName().contains(suffix)) // 仅仅搜索包含后缀suffix的文件 55 runThreadPool(x, content);// 使用多线程进行文件内容搜索 56 } 57 } 58 } 59 60 }
效果图:
标签:== -- break com public generate Stub trace nbsp
原文地址:https://www.cnblogs.com/gilgamesh-hjb/p/12237564.html