Import Java.io.file;public class Readdirectory {//The number of layers where the file resides private int filelevel; /** * Generate output format * @param name output file name or directory name * @param level output filename or hierarchy of directory name * @return Output string */public string Createprintstr (string name, int. level) {//output prefix string PrintS TR = ""; Indent by hierarchy for (int i = 0; i < level; I + +) {printstr = Printstr + ""; } printstr = Printstr + "-" + name; return printstr; /** * Output Initial given directory * @param dirpath given directory */public void Printdir (String dirpath) { Splits a given directory string[] dirnamelist = Dirpath.split ("\\\\"); Set the file level base filelevel = Dirnamelist.length; Output by format for (int i = 0; i < dirnamelist.length; i + +) {SysTem.out.println (Createprintstr (dirnamelist[i], i)); }}/** * Output files in a given directory, including files in subdirectories * @param dirpath given directory */public void ReadFile (String Dirpath) {//Create a file object for the files in the current directory. FileName = new file (Dirpath); Gets an array of file objects representing all the files in the directory file[] list = File.listfiles (); Traverse the file array for (int i = 0; i < list.length; i++) {if (List.isdirectory ()) { System.out.println (Createprintstr (List.getname (), filelevel)); Filelevel + +; Recursive subdirectory ReadFile (List.getpath ()); Filelevel--; } else {System.out.println (Createprintstr (List.getname (), filelevel)); }}} public static void Main (string[] args) {readdirectory rd = new readdirectory (); String Dirpath = "d:\\ Youdao dictionary"; Rd.printdir (Dirpath); Rd.readfile (Dirpath); }}
The output results are as follows:
Java traverses the given directory, and the tree outputs all files, including files in subdirectories