利用JDK8的新特性計算某個目錄下的檔案中包含字串的次數
阿新 • • 發佈:2019-02-09
需求:計算某個字串在某個資料夾中出現的次數。**這篇文章利用了JDK1.8的新特性Stream流和Lambda表示式並結合了執行緒池的使用。**
package com.zkn.fullstacktraining.seventh;
import javafx.util.Pair;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.*;
import java.util.stream.Collectors;
/**
* Created by zkn on 2017/2/5.
*/
public class SearchStringByThreadPool {
public static void main(String[] args) {
try {
//建立5個固定執行緒的執行緒池
ExecutorService executorService = Executors.newFixedThreadPool(5);
List<Future<Pair<String, Integer>>> listFile =
// 這裡是取所傳入目錄的最多四層,如果不知道這個API的話需要遞迴去做。
Files.walk(Paths.get("D:\\CUST\\workspace\\JavaCore\\FullStackTraining\\src\\main\\java\\com\\zkn"), 4)
.filter(file -> !Files.isDirectory(file) && file.toString().endsWith("java"))//檔案資料夾和不是java的檔案
.map(file -> (Callable<Pair<String, Integer>>) () -> {// 建立N多個Callable實現類
Pair<String, Integer> pair = null;//這裡的鍵值對用pair比用Map更好一些
try {
Optional optional = Files.lines(file).map(str -> {
int count = 0;
int index = str.indexOf("main");
if (index >= 0) {
//這裡需要迴圈計算,因為可能在某一行中會出現多次
do {
count++;
} while ((index = str.indexOf("main", index + 1)) > 0);
}
return count;
}).reduce(Integer::sum);//合併最終的計算結果
int count = optional.isPresent() ? (int) optional.get() :0;
pair = new Pair<>(file.toString(),count);
} catch (IOException e) {
e.printStackTrace();
}
return pair == null ? new Pair<>("", 0) : pair;
})
.map(file -> executorService.submit(file))//提交給執行緒池進行處理
.collect(Collectors.toList());
listFile.stream().map(file -> {
Pair<String, Integer> pair = null;
try {
pair = file.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return pair == null ? new Pair<>("", 0) : pair;
})
.filter(file -> file.getValue() > 0)//過濾掉不包含字串的檔案
.sorted((s1, s2) -> Integer.compare(s2.getValue(), s1.getValue()))//從大到小排序
.forEach(file -> System.out.println(String.format("%d次出現在%s檔案中", file.getValue(), file.getKey())));
//關閉執行緒池
executorService.shutdown();
} catch (Exception e) {
e.printStackTrace();
}
}
public void test() {
String str = "mainmainmainmainmain";
}
}