Two Methods for Traversing folders in Java

Source: Internet
Author: User
A. Do not use recursion:

Import java. Io. file;

Import java. util. Collections list;

Public class filesystem {

Public static void main (string [] ARGs ){

Long A = system. currenttimemillis ();

Jsonlist list = new jsonlist ();

File dir = new file ("C:" "Java """);

File 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 TMP;

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. listfiles ();

If (Files = NULL)

return;

for (INT I = 0; I

If (files [I]. isdirectory () {

refreshfilelist (files [I]. getabsolutepath ();

}else {

string strfilename = files [I]. getabsolutepath (). tolowercase ();

system. out. println ("---" + strfilename);

filelist. add (files [I]. getabsolutepath ());

}

conclusion: the Recursive Method B has better performance.

Related Article

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.