獻給那些在一堆文本文件中找不到自己想要的字段的同行
package util;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
/**
* @Author Daniel
* @Description 自己寫的一個util,有需要的自取
**/
public class FindWords {
//總數
public static int count = 0;
public static void main(String[] args) {
findFile(new File("F:\\test\\test2"), "a");
}
public static void findFile(File file, String word) {
File[] listFiles = file.listFiles();
for (int i = 0; i < listFiles.length; i++) {
if (listFiles[i].isDirectory())
//如果是文件夾則進行遞歸
findFile(listFiles[i], word);
//如果文件存在或者能讀則開始檢索
if (listFiles[i].exists() || listFiles[i].canRead()) {
try {
int j = 0, k = 0, ch = 0;
String str = null;
FileReader in = new FileReader(listFiles[i]);
while ((ch = in.read()) != -1) {
//拼接一次比較一次
str += (char) ch;
}
if (str != null) {
while (str.indexOf(word, j) != -1) {
k++;
j = str.indexOf(word, j) + 1; // 返回第一次出現的指定子字符串在此字符串中的索引
}
}
if (k > 0) {
System.out.println("路徑:" + listFiles[i].getAbsolutePath() + "中有" + k + "個" + word);
count++;
}
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
if (count != 0) {
System.out.println("“" + word + "”以一共在" + count + "個文件中出現了");
} else {
System.out.println("“" + word + "”不存在!");
}
}
}