All files under the JAVA Traversal folder (recursive calls and non-recursive calls)
1. Do not use recursive method calls.
public void TraverseFolder1 (String path) {int filenum = 0, foldernum = 0; File File = new file (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); filenum++; } else {System.out.println ("file:" + File2.getabsolutepath ()); foldernum++; }} File Temp_file; while (!list.isempty ()) {temp_file = List.removefirst (); Files = Temp_file.listfiles (); for (File file2:files) {if (File2.isdirectory ()) {System.out.println ("folder:") + File2.getabsolutepath ()); List.add (file2); filenum++; } else {System.out.println ("file:" + File2.getabsolutepath ()); foldernum++; }}}} else {System.out.println ("file does not exist!"); } System.out.println ("folder total:" + foldernum + ", file total:" + filenum); }
2. Use recursive method calls.
public void TraverseFolder2 (String path) { file File = new file (path); if (file.exists ()) { file[] files = file.listfiles (); if (Files.length = = 0) { System.out.println ("folder is empty!"); return; } else {for (File file2:files) { if (file2.isdirectory ()) { System.out.println ("folder:" + File2.getabsolutepath ()); TraverseFolder2 (File2.getabsolutepath ()); } else { System.out.println ("file:" + File2.getabsolutepath ());}}}} else { System.out.println ("file does not exist!");} }
3,
public static list<file> getfilelist (String strpath) { file dir = new File (strpath); file[] files = dir.listfiles (); The files in the directory are all placed in the array if (Files! = null) {for (int i = 0; i < files.length; i++) { String fileName = files[i]. GetName (); if (Files[i].isdirectory ()) {//Determines whether the file or folder Getfilelist (Files[i].getabsolutepath ());//Gets the 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 { continue;}} } return filelist; }
Original link: http://www.cnblogs.com/azhqiang/p/4596793.html
JAVA traverse all files under a folder