Title: Given a directory, it is required to output subdirectories and sub-files under this directory
Logic:
- First, the given is not a valid directory, if not, prompt for the given error
- If it is a directory, then use File.listfile () to get an array of file names in this directory
- Loop through the output of this array element
- After the output name, then determine whether the element is a file or a directory
- If it is a directory, continue calling this method to output subdirectories
The code is as follows:
/*** Output all sub-directories and sub-files in the specified directory * *@authorLGB **/ Public classHellofile { Public Static voidMain (string[] args) {Printfile (NewFile ("D:\\test")); } Public Static voidprintfile (file file) {if(File.isfile ()) {System.out.println ("You are given a file");//determines whether a given directory is a valid directory, if not, the output hint}Else{file[] filelists= File.listfiles ();//if it is a directory, get the content collection under that directory for(inti = 0; i < filelists.length; i++) {//iterate through the contents of this collectionSystem.out.println (Filelists[i].getname ());//output element name if(Filelists[i].isdirectory ()) {//The judging element is not a directoryPrintfile (Filelists[i]);//if it is a directory, continue calling this method to output its subdirectories } } } }}
Executed successfully, the result is correct, but the appearance is too ugly,
We're going to need to add indentation and retrofit.
Public classHellofile { Public Static voidMain (string[] args) {Printfile (NewFile ("D:\\test"), 1); } Public Static voidPrintfile (File file,inttab) { if(File.isfile ()) {System.out.println ("You are given a file");//determines whether a given directory is a valid directory, if not, the output hint}Else{file[] filelists= File.listfiles ();//if it is a directory, get the content collection under that directory for(inti = 0; i < filelists.length; i++) {//iterate through the contents of this collection for(intj = 0; J < Tab; J + +) {//Output IndentSystem.out.print ("|---"); } System.out.println (Filelists[i].getname ()); //output element name if(Filelists[i].isdirectory ()) {//The judging element is not a directoryPrintfile (filelists[i],tab+1);//if it is a directory, continue calling this method to output its subdirectories, because it is its subdirectory, so the number of indents + 1 } } } }}
The result is:
Java output subdirectories and sub-files under the specified directory