暂时不支持word,会乱码
package com.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class FileContentSearch {
private static String FileName = "D:\\dataword";// 文件夹名字
private static String FileEnd = "txt";// 文件名称后缀 txt sql bat
private static String SearchStr = "ceshi";//要查找的字符串
private static Boolean IngronCase = true;// 是否区分大小写
private static List<String> pathlist = new ArrayList<>();
public static void main(String[] args) {
List<String> resultList = new ArrayList<>();
int count = 0;
pathlist = getFileList(FileName);
for(int k=0;k<pathlist.size();k++) {
File file = new File(pathlist.get(k));
if (file.exists()) {
String s = file.toString();
count++;
System.out.println("正在读取第" + count + "个文件" + s);
/* 读取数据 */
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File(s)), "GB2312"));
String lineTxt = null;
while ((lineTxt = br.readLine()) != null) {
if (IngronCase) {
if (lineTxt.contains(SearchStr)) {
resultList.add("在【" + s + "】文件中找到了" + SearchStr + "在第" + count + "行");
break;
}
} else {
if (lineTxt.toLowerCase().contains(SearchStr.toLowerCase())) {
resultList.add("在【" + s + "】文件中找到了" + SearchStr + "在第" + count + "行");
break;
}
}
}
br.close();
} catch (Exception e) {
// TODO: handle exception
System.err.println("读取文件错误 :" + e);
}
}
}
System.out.println("===============输出结果===============");
// 输出结果
for (int i = 0; i < resultList.size(); i++) {
System.out.println(resultList.get(i));
}
}
public static List<String> getFileList(String strPath) {
File dir = new File(strPath);
File[] files = dir.listFiles(); // 该文件目录下文件全部放入数组
if (files != null) {
for (int i = 0; i < files.length; i++) {
String fileName = files[i].getName();
if (files[i].isDirectory()) { // 判断是文件还是文件夹
getFileList(files[i].getAbsolutePath()); // 获取文件绝对路径
} else if (fileName.endsWith("."+FileEnd)) { // 判断文件名是否以.avi结尾
String strFileName = files[i].getAbsolutePath();
pathlist.add(strFileName);
} else {
continue;
}
}
}
return pathlist;
}
}