Java traversal files in a folder

Source: Internet
Author: User

2 ways to traverse a folder in Java:

A. Do not use recursion:

Import;import Java.util.linkedlist;public class FileSystem {public static void main (string[] args) {                Long a = System.currenttimemillis ();        LinkedList list = new LinkedList ();        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 (f                    Ile[i]);                Else System.out.println (File[i].getabsolutepath ());          }  } else {System.out.println (Tmp.getabsolutepath ());    }} System.out.println (System.currenttimemillis ()-a);                       }}

B. Using recursion:

 Import;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 < files.length; i++) {if (Files[i].isdirectory ()) {refreshfilelist (file             S[i].getabsolutepath ());                } else {String strFileName = Files[i].getabsolutepath (). toLowerCase ();                SYSTEM.OUT.PRINTLN ("---" +strfilename);                                Filelist.add (Files[i].getabsolutepath ()); }}} Conclusion: After testing, using recursive method B has a relatively good performance. 

Java traverse files in folder

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: 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.