public class SearchKey {
// the number of appear time.
private static int count;
public static void fileList(PrintWriter writer, File file, String key) {
File[] files = file.listFiles();
for (File childFile : files) {
// judge the file is a directory or not
if (childFile.isDirectory()) {
fileList(writer, childFile, key);
} else {
String fileName = childFile.getAbsolutePath();
// the type of search file(.java, .jsp)
if (fileName.endsWith(".java") || fileName.endsWith(".jsp")) {
findKey(writer, childFile, key);
}
}
}
}
// print the file name and the line that the key word appeared and the line number
public static void findKey(PrintWriter writer, File file, String key) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String fileName = file.getAbsolutePath();
String tempString = null;
int line = 1;
while ((tempString = reader.readLine()) != null) {
if (tempString.contains("*" + key + "*") || tempString.contains(*"* + key + *"*)) {
if (count != 0) {
writer.write(key);
}
writer.write("\t" + fileName);
writer.write("\t" + "line " + line + "\t" + tempString.trim() + "\n");
count ++;
}
line ++;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
File file = new File("C:\\src\\git\\dmp");// the folder will be search
PrintWriter writer = null;
try {
writer = new PrintWriter(new File("C:\\src\\git\\I18N.txt"));// print the message to this txt file.
count = 0;
writer.write(key);
fileList(writer, file, key);
if (count == 0) {
writer.write("\n");
}
writer.write("\n");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}