This article describes the Java implementation of recursive file list method. Share to everyone for your reference. Specifically as follows:
Filelisting.java is as follows:
Import java.util.*;
Import java.io.*;
/** * Recursive file listing under a specified directory. * @author javapractices.com * @author Alex Wong * @author Anonymous user */public final class FileListing {/** * De
Monstrate use.
* @param Aargs-<tt>aArgs[0]</tt> is the "full name of" an existing * directory which can be read.
*/public static void Main (String ... aargs) throws FileNotFoundException {file startingdirectory= new file (aargs[0));
list<file> files = filelisting.getfilelisting (startingdirectory);
Print out all file names, in the ' Order of ' File.compareto () for (file file:files) {System.out.println (file); }/** * Recursively walk a directory and return a List of all * Files found;
The List is sorted using File.compareto ().
* * @param astartingdir is a valid directory, which can be read. */static public list<file> getfilelisting (File astartingdir) throws FileNotFoundException {Validatedirecto Ry (AStaRTINGDIR);
list<file> result = Getfilelistingnosort (Astartingdir);
Collections.sort (result);
return result; }//private//static private list<file> Getfilelistingnosort (File astartingdir) throws Filenotfoundexceptio
n {list<file> result = new arraylist<file> ();
file[] Filesanddirs = Astartingdir.listfiles ();
list<file> filesdirs = arrays.aslist (filesanddirs); for (file file:filesdirs) {result.add (file);//always Add, even if directory (! file.isfile ()) {//must b
e a directory//recursive call!
list<file> deeperlist = Getfilelistingnosort (File);
Result.addall (deeperlist);
} return result;
/** * Directory is valid if it exists, does isn't represent a file, and can be read. */static private void Validatedirectory (File adirectory) throws FileNotFoundException {if (adirectory = null)
{throw new IllegalArgumentException ("Directory should not being null."); } if (!adirectory.Exists ()) {throw new FileNotFoundException ("Directory does not exist:" + adirectory);
} if (!adirectory.isdirectory ()) {throw new IllegalArgumentException ("Not a directory:" + adirectory);
} if (!adirectory.canread ()) {throw new IllegalArgumentException ("Directory cannot be read:" + adirectory);
}
}
}
I hope this article will help you with your Java programming.