(Transferred from: http://blog.csdn.net/gangwazi0525/article/details/7569701)
1 ImportJava.io.File;2 3 Public classReaddirectory {4 //the number of layers on which the file resides5 Private intFilelevel;6 7 /**8 * Generate output format9 * @paramName the file name or directory name of the outputTen * @paramlevel output file name or directory name One * @returnthe output string A */ - PublicString Createprintstr (string name,intLevel ) { - //prefix of output theString printstr = ""; - //Indent by Hierarchy - for(inti = 0; I < level; i + +) { -Printstr = Printstr + ""; + } -Printstr = Printstr + "-" +name; + returnPrintstr; A } at - /** - * Output The initial given directory - * @paramDirpath a given directory - */ - Public voidPrintdir (String dirpath) { in //To split a given directory -string[] Dirnamelist = Dirpath.split ("\\\\"); to //set the base of the file level +Filelevel =dirnamelist.length; - //output by Format the for(inti = 0; i < dirnamelist.length; i + +) { * System.out.println (Createprintstr (dirnamelist[i], i)); $ }Panax Notoginseng } - the /** + * Output files in a given directory, including files in sub-directories A * @paramDirpath a given directory the */ + Public voidreadFile (String dirpath) { - //Create a file object for the files in the current directory $File File =NewFile (dirpath); $ //gets an array of file objects representing all the files in the directory -file[] List =file.listfiles (); - //traversing a file array the for(inti = 0; i < list.length; i++) { - if(List.isdirectory ()) {Wuyi System.out.println (Createprintstr (List.getname (), filelevel)); theFilelevel + +; - //Recursive sub-directories Wu ReadFile (List.getpath ()); -Filelevel--; About}Else { $ System.out.println (Createprintstr (List.getname (), filelevel)); - } - } - } A + Public Static voidMain (string[] args) { theReaddirectory rd =Newreaddirectory (); -String Dirpath = "d:\\ Youdao dictionary"; $ Rd.printdir (dirpath); the Rd.readfile (dirpath); the } the}
The output results are as follows:
Java traverses the given directory, and the tree outputs all files, including files in subdirectories