运用线程池来查找含有指定字符的文件

运用线程池来查找含有指定字符的文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package threadPool;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**

* @author 刘建雯
*/

public class FileSearching {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("[ Please input path ]");
String path = scanner.nextLine();
System.out.println("[ Please input end words ]");
String endWords = scanner.nextLine();
System.out.println("[ Please input the special words you wanna find ]");
String specialWords = scanner.nextLine();
FileSearching fileSearching = new FileSearching();
fileSearching.fileSearch(path,endWords,specialWords);
}

private static int count = 0;
private ThreadPoolExecutor threadPool = new ThreadPoolExecutor(10,20,30, TimeUnit.SECONDS, new LinkedBlockingQueue<>());

public void fileSearch(String path, String endStr, String specialStr){
File filePath = new File(path);
if(!filePath.exists()){
System.out.println("[warning] file not exist");
return;
}
if(!filePath.isDirectory()){
if(filePath.getName().endsWith(endStr)){
threadPool.execute(() -> {
try {
char[] content = new char[(int)filePath.length()];
FileReader fileReader = new FileReader(filePath);
fileReader.read(content);
if(String.valueOf(content).contains(specialStr)){
System.out.println("[file found] "+filePath.getAbsolutePath());
FileSearching.countUp();
}
} catch (IOException e) {
e.printStackTrace();
}
});
}
}else{
File[] files = filePath.listFiles();
assert files != null;
for(File file:files){
fileSearch(file.getAbsolutePath(),endStr,specialStr);
}
}
System.out.println("find "+count+" files end with "+endStr+" and contain \""+specialStr+"\"");
}

private static void countUp(){
count++;
}

}

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!