File directory Query
Returns a file array using the Listfiles () method in the file class. has used a recursive search combined with isdirectory () to make a critical point. You can enter a multilevel directory query and then use a StringBuilder append method to get the file directory to return its ToString function to return the file directory name. The Append method of StringBuilder here is because if you use string+=, you will consume memory. This method is faster, but not for multi-threading, and it is recommended to use StringBuffer if such synchronization is required. The effect is as shown in the figure:
The implementation code is as follows:
Package Cn.hncu.io3;
Import Java.io.File;
public class ShowDir2 {public
static void Main (string[] args) {
file Dir=new file ("E:/bcde");
Showdir (dir,0);
}
private static void Showdir (File dir,int count) {
System.out.println (Getspace (count) +dir.getname ());
count++;
File files[]=dir.listfiles ();
if (files!=null) {for
(File f:files) {
if (f.isdirectory ()) {
showdir (f,count);
} else{
System.out.println (Getspace (count) +f.getname ());
}}} private static String getspace (int count) {
StringBuilder sb=new StringBuilder ();
for (int i = 0; i < count; i++) {
sb.append ("|--"),/////////With sb+= memory, this addition is a bit better
}
return sb.tostring ();
}
}