package search; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; public class KeyWordSearch { static String dir = "D:\\workspace\\OPlayer"; // 被查找的目录 static String keyWord = "init_decoders"; // 被搜索到关键字 public static void main(String args[]) { File file = new File(dir); keyWordSearch(file); } private static void keyWordSearch(File file) { File[] files = file.listFiles(); for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { keyWordSearch(files[i]); // 如果该file是目录,递归 } else { fileSearch(files[i]); // 如果该file是文件,查找 } } } private static void fileSearch(File file) { try { BufferedReader br = new BufferedReader(new FileReader(file)); String temp = ""; int i = 0; while ((temp = br.readLine()) != null) { i++; if (temp.indexOf(keyWord) != -1) { // 如果改行包含关键字,输出文件名字和行号 System.out.println(file.getPath() + " --- in line ---> " + i); br.close(); return; } } br.close(); } catch (Exception e) { e.printStackTrace(); } } }