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)