Scope of application: only for searching in text documents (such as TXT, Java, C, etc., does not apply to Doc, XLS, etc.), you can nest folders. However, it is not supported in Chinese.
For example: folder: F:/demo
Sub-folders: F:/demo/ert
Find results:
Finally, enclose all the code:
1 PackageCom.stafen.main;2 3 ImportJava.io.File;4 Importjava.io.IOException;5 Importjava.util.ArrayList;6 Importjava.util.Collection;7 Importjava.util.List;8 9 Importorg.apache.commons.io.FileUtils;Ten Importorg.apache.commons.io.IOUtils; One A Public classTest { -/** the string to find **/ - Private StaticString strsearch = "Qcnea"; the/** the name of the directory to find **/ - Private StaticString strpath = "E:/project"; - -@SuppressWarnings ("Unchecked") + Public Static voidMain (string[] args) { - +File Searchdir =NewFile (strpath); Alist<search> list =NewArraylist<search>(); at Try { -collection<file> files = fileutils.listfiles (Searchdir,NULL,true); -List<string> lines =NULL; - for(File file:files) { - Try { -Lines = fileutils.readlines (file, "UTF-8"); in}Catch(IOException e) { - e.printstacktrace (); to } + for(inti = 0; I < lines.size (); i++) { - if(Lines.get (i). INDEXOF (strsearch)! =-1) { theSearch s =NewSearch (); * S.setfilename (File.getpath ()); $S.setline (i + 1));Panax Notoginseng s.setcontent (Lines.get (i)); - List.add (s); the } + } A } theStringBuffer SB =NewStringBuffer (); + if(list.size () = = 0) { -System.out.println ("" did not find the string!) 】"); $ return ; $ } - for(Search s:list) { -Sb.append ("File path:" + s.getfilename () + "\ n lines:" + s.getline () + "\ n Line contents:" +s.getcontent ()). append (ioutils.line_separator); theSb.append ("---------------------------------------------------------------------\ n"); - }Wuyi System.out.println (sb.tostring ()); the}Catch(Exception e) { -System.out.println ("" did not find the directory! 】"); Wu } - } About $}
Search.java file
Public classSearch {PrivateString filename; Private intLine ; PrivateString content; PublicString GetFileName () {returnfilename; } Public voidsetfilename (String filename) { This. FileName =filename; } PublicString getcontent () {returncontent; } Public voidsetcontent (String content) { This. Content =content; } Public voidSetline (intLine ) { This. Line =Line ; } Public intGetLine () {returnLine ; }}
Find a fixed string in a local file (Java)