适用范围:只适用于在文本文档中查找(如,txt、java、c等等,并不适用与doc、xls等等这些文件),可嵌套文件夹。但是对中文不支持。
例如:文件夹:F:/demo
子文件夹:F:/demo/ert
查找结果:
最后附上全部代码:
package com.stafen.main; import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List; import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils; public class Test {
/** 要查找的字符串 **/
private static String strSearch = "QCNEA";
/** 要查找的目录名称 **/
private static String strPath = "E:/Project"; @SuppressWarnings("unchecked")
public static void main(String[] args) { File searchDir = new File(strPath);
List<Search> list = new ArrayList<Search>();
try {
Collection<File> files = FileUtils.listFiles(searchDir, null, true);
List<String> lines = null;
for (File file : files) {
try {
lines = FileUtils.readLines(file, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
for (int i = 0; i < lines.size(); i++) {
if (lines.get(i).indexOf(strSearch) != -1) {
Search s = new Search();
s.setFilename(file.getPath());
s.setLine(i + 1);
s.setContent(lines.get(i));
list.add(s);
}
}
}
StringBuffer sb = new StringBuffer();
if(list.size() == 0) {
System.out.println("【没有查到该字符串!】");
return ;
}
for (Search s : list) {
sb.append("文件路径:" + s.getFilename() + "\n行数:" + s.getLine() + " \n所在行内容:" + s.getContent()).append(IOUtils.LINE_SEPARATOR);
sb.append("---------------------------------------------------------------------\n");
}
System.out.println(sb.toString());
} catch (Exception e) {
System.out.println("【没有找到该目录!】");
}
} }
Search.java文件
public class Search { private String filename;
private int line;
private String content; public String getFilename() {
return filename;
} public void setFilename(String filename) {
this.filename = filename;
} public String getContent() {
return content;
} public void setContent(String content) {
this.content = content;
} public void setLine(int line) {
this.line = line;
} public int getLine() {
return line;
} }