递归搜索文件

package mypackage;
import java.io.File;
public class DeleteDirectory extends File
{
 private String directoryNameToDelete = "b";
 
 public DeleteDirectory(String fileName)
 {
  super(fileName);
 }
 
 
 //从自身开始,搜索特定名称的目录,找到则删除
 public void searchDirectory()
 {
  //如果此文件对象是目录
  if(isDirectory())
  {
   //找到了,删除文件对象所表示的目录
   if(getName().equals(this.directoryNameToDelete))
   {
    deleteDirectory();
   }
   //此目录不是我们想要找的,则对该目录下的所有子目录对象进行递归搜索
   else 
   {
    String listFiles[] = list();
    
    for(String entry : listFiles)
    {
     DeleteDirectory child = new DeleteDirectory(getPath() + separatorChar + entry);
     
     //递归搜索
      child.searchDirectory();
    }
   }
  }
 }
 
 
 //删除目录,及其下面包含的所有目录和文件
 public void deleteDirectory()
 {
  boolean isDeleted = delete();   //先删除自身
  
  //未删除成功,则表示此目录不为空,则对此目录下的所有目录和文件进行递归删除
  if(!isDeleted)
  {
   String fileNames[] = list();
   
   for(String entry : fileNames)
   {
    DeleteDirectory child = new DeleteDirectory(getPath() + separatorChar + entry);
    
    if(child.isDirectory())
    {
     child.deleteDirectory(); //递归删除
    } 
    else
    {
     child.delete(); 
    }
   }
   
   delete(); //递归删除子目录及文件后,再删除自身
  }
 }
 
 
 public static void main(String[] args)
 {
  DeleteDirectory lf = new DeleteDirectory("E://a");
  lf.searchDirectory();
 }
}
相关文章
相关标签/搜索