Two Methods for Java to traverse folders

Source: Internet
Author: User

. do not use recursion:

Import Java. io. file; import Java. util. optional list; public class filesystem {public static void main (string [] ARGs) {long a = system. currenttimemillis (); region list = new region list (); file dir = new file ("C: \ Java \"); file [] = dir. listfiles (); For (INT I = 0; I <file. length; I ++) {If (file [I]. isdirectory () list. add (file [I]); else system. out. println (file [I]. getabsolutepath ();} file TM P; while (! List. isempty () {TMP = List. removefirst (); If (TMP. isdirectory () {file = TMP. listfiles (); If (file = NULL) continue; For (INT I = 0; I <file. length; I ++) {If (file [I]. isdirectory () list. add (file [I]); else system. out. println (file [I]. getabsolutepath () ;}} else {system. out. println (TMP. getabsolutepath () ;}} system. out. println (system. currenttimemillis ()-);}}
 

B. recursion:

 Import Java. io. file; import Java. util. arraylist; public class filesystem1 {Private Static arraylist filelist = new arraylist (); public static void main (string [] ARGs) {long a = system. currenttimemillis (); refreshfilelist ("C: \ Java"); system. out. println (system. currenttimemillis ()-A);} public static void refreshfilelist (string strpath) {file dir = new file (strpath); file [] files = dir. listf Iles (); If (Files = NULL) return; For (INT I = 0; I 
  
    conclusion: Recursive Method B has better performance. 
  

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.