使用多線程,遍歷目錄下所有的文件(包括子文件夾),找出文件內容包括search字符串的的那些文件,並打印出來。這里使用匿名內部類創建線程。
import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; public class FileSearch { public static void search(File folder, String search){ // if(folder.length()==0) // return; if(folder.exists()){ File[] files = folder.listFiles(); for(File file:files){ if(file.isDirectory()){ search(file.getAbsoluteFile(),search); }else{ //如果是文件,則對文件進行查找,查找到的話就輸出文件路徑 System.out.println("文件下包含的文件:"+file.getAbsolutePath()); Thread thread = new Thread(){ public void run() { try { FileReader reader=new FileReader(file); String str=""; //記錄文件的所有字符 int ch=0,j=0; while((ch=reader.read())!=-1){ str += (char) ch; } if (str != null) { if (str.indexOf(search, 0) != -1) //從開頭開始索引,找到一個就輸出路徑 { System.out.println("查找到字符串,文件:"+file.getAbsolutePath()); } } } catch (FileNotFoundException e) { e.printStackTrace(); }catch (Exception e) { e.printStackTrace(); } } }; thread.start(); //啟動查找線程 } } } } public static void main(String[] args) { search(new File("E:\\Coding\\JAVA\\MultilThread\\MultilThreadLearn\\src\\test"),"testnidauye"); } }