Java non-recursive way to get all the files in the directory (including directories)

Source: Internet
Author: User

0. Analysis of Ideas

For the given file, look at all of the directories below it, place all the directories under this directory in the directory collection to be traversed, remove the directory traversal from the collection each time, and if the directory is placed in the directory again for traversal.

One, the code
    /*** Non-recursive way to get all the files in the directory <br> * The path obtained by this method is not listed as a directory--file * *@paramDirpath directory path *@returnA collection of all files and directories under the specified directory*/     Public StaticList<file>listallfile (String dirpath) {LinkedList<File> Allfiles =NewLinkedlist<>(); if("". Equals (Dirpath) | |NULL==Dirpath) {            returnAllfiles; } File File=NewFile (Dirpath); Allfiles.add (file);//Add your own        if(File.isfile ()) {returnAllfiles; } file[] FileList=File.listfiles (); if(FileList = =NULL|| Filelist.length = = 0) {            returnAllfiles; }        //put the first fetched file and directory into the total collectionAllfiles.addall (Arrays.aslist (fileList)); //declaring a collection of stored directoriesLinkedlist<file> dirchecklist =NewLinkedlist<>(); //working with first-level catalogs         for(File curfile:filelist) {if(Curfile.isdirectory ()) {Dirchecklist.add (curfile); }        }         while(!Dirchecklist.isempty ()) {File RemoveDir= Dirchecklist.removefirst ();//Remove the first catalogfile[] Removedirfilelist =Removedir.listfiles (); if(Removedirfilelist = =NULL) {                Continue; }            //Add all the files and directories found to the total collectionAllfiles.addall (Arrays.aslist (removedirfilelist));  for(File curfile:removedirfilelist) {if(Curfile.isdirectory ()) {Dirchecklist.add (curfile); }            }        }        returnAllfiles; }

Java non-recursive way to get all the files in the directory (including directories)

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.