Original: http://www.yi-dao.com/works/model/sample/findfiles.htm traverses deep-level tree structure. The example here is to find the "java.exe" file in all local hard drives. When you look for a specific file to a deep directory, it is easy to traverse it through constant iteration.
Import java.io.file;
Public class filesearchtool {public static void main (string "args) {string TOFIND =" java.exe "; file [] roots = file.listroots (); for (int i = 0; i Public Static Void SearchList (File File, String Tofind) {file [] files = file.listfiles (); if (files! = null) {for (INT i = 0; I The above code surface is visually optimistic to complete the task, but the above method is invalid. The depth and breadth of the directory is ignored, and resources are constantly allocated during recursive process (file [] files = file.listfiles (), and only the current work is only ended when the deeper recursive ends can end the current work and release these resources. This makes it possible to cause stack overflow and JVM to stop working. In order to solve such problems, you should try to avoid using recursive. Methods that don't have to recurrently do not allocate a lot of resources is effective. Below is the program that looks for "java.exe" in the hard disk without recursive. When you analyze the state machine of this process, please see: http://www.yi-dao.com/Works/model/sample/findfiles.ydm Download this document, use "Easy Model" to open, Easy Road Model Download: http: / / www.sharebank.com.cn/soft/soft_view.php?id=11135 ---------------------------------------------------------------------------------------------------------------------------------------------------- ----------------------- Public class test {public static void main (String [] args) {file [] roots = file.listroots (); string Nametofind = "java.exe"; for (int i = 0; i Public Boolean Accept (File Pathname) {Return (Pathname! = null) && pathname.isfile () && tofind.equalsignorecase (Pathname.GetName ());}} MyFileFilter fileFilter = new MyFileFilter (nameToFind); MyDirFilter dirFilter = new MyDirFilter (); int state = FIND_SUB; // start LinkedHashSet found = new LinkedHashSet (); while (! State = FIND_END) {File dir = (File) curPath.pop (); // current directory // system.out.println (Dir.getabsolutePath ()); if (state == find_sub) {// Find sub-node file [] subdirs = dir.listfiles (Dirfilter); if (Subdirs == NULL || Subdirs.Length == 0) {// No child node curpath.push (dir); state = find_sib; // Next time you need to find the same level node} else {curpath.push (DIR); Curpath. Push (Subdirs [0]); state = find_sub;}}}}} else if (state == find_sib) {// Find the same level node file [] files = dir.listfiles (filefilter); if (files! = null) {for (INT i = 0; i