All files under the JAVA Traversal folder (recursive calls and non-recursive calls)
1. Do not use recursive method calls.
PublicvoidTraverseFolder1 (String path) {int filenum = 0, Foldernum = 0; File File =NewFile (path);If(File.exists ()) {linkedlist<file> list =New linkedlist<file>(); file[] Files =File.listfiles ();For(File file2:files) {If(File2.isdirectory ()) {System.out.println ("folder:" +File2.getabsolutepath ()); List.add (file2); foldenum++; }Else{System.out.println ("File:" +File2.getabsolutepath ()); filenum++; }} File Temp_file;while (!List.isEmpty ()) {temp_file = List.removefirst (); files = Temp_file.listfiles (); Span style= "color: #0000ff;" >forif (File2.isdirectory ()) {System.out.println ("folder:" +else File2.getabsolutepath ()); Filenum++else); } System.out.println ("folder total:" + foldernum + ", file total:" + FileNum);}
2. Use recursive method calls.
PublicvoidTraverseFolder2 (String path) {File File =NewFile (path);If(File.exists ()) {file[] files =File.listfiles ();if (files.length = = 0); returnelse {for (File file2:files) {if (File2.isdirectory ()) { System.out.println ("folder:" + File2.getabsolutepath ()); TraverseFolder2 (File2.getabsolutepath ()); } else File2.getabsolutepath ()); }}}} else); } }
3,
PublicStatic list<file>Getfilelist (String strpath) {File dir =NewFile (strpath); file[] files = dir.listfiles ();//All the files in the file directory are put into the arrayif (Files! =Null) {for (int i = 0; i < files.length; i++) {String FileName = Files[i].getname (); if (Files[i].isdirectory ()) {// Determine whether the file or folder Getfilelist (Files[i].getabsolutepath ()); // Get file absolute path} else if (Filename.endswith ("avi")) {// Determine if the file name ends with an. avi String strfilename = Files[i].getabsolutepath (); SYSTEM.OUT.PRINTLN ("---" + strFileName); Filelist.add (Files[i]);} else {continuereturn FileList;}
JAVA traverse all files under a folder