JAVA利用递归删除文件和文件夹

来源:互联网 发布:迅捷网络初始密码 编辑:程序博客网 时间:2024/04/29 07:32
看了一个网友写的JAVA删除文件例子,觉得写得很罗嗦,这里重写以下,就当练练手,呵呵。

import java.io.*;
/**
 * it provides some util methods to operate file or folder.
 * @author zhangxuebao
 *
 */
public class FiltUtil {
 
 /**
  * delete the specified file or folder.if the folder has sub items,
  * the items alsowill be deleted .
  * @param f the file or folder.
  * @throws IOException
  */
 public static void deleteFile(File f) throws IOException
 { 
  if(!f.exists())
   throw new IOException("指定文件或者目录不存在:"+f.getName());
  
  //如果是文件夹,删除其中所有子项目
  if(f.isDirectory())
  {
   File subs[] = f.listFiles();     
   for (int i = 0; i < subs.length; i++)
    deleteFile(subs[i]);
  }
  
  //直接删除
  f.delete();
 }
}



////////////////////////////////原版本//////////////////////////
一个File对象,如果是目录,那么delete()方法要求目录已经是空的,否则不能删除。为了不管如何都删除一个指定文件夹下的所有内容,于是有了今天随手的一个小段子,算是初学Java的小练习:

import java.io.*;

public class DeleteAll {  //删除文件夹下所有内容,包括此文件夹  public void delAll(File f) throws IOException {    if(!f.exists())//文件夹不存在不存在      throw new IOException("指定目录不存在:"+f.getName());

    boolean rslt=true;//保存中间结果    if(!(rslt=f.delete())){//先尝试直接删除      //若文件夹非空。枚举、递归删除里面内容      File subs[] = f.listFiles();      for (int i = 0; i <= subs.length - 1; i++) {        if (subs[i].isDirectory())          delAll(subs[i]);//递归删除子文件夹内容        rslt = subs[i].delete();//删除子文件夹本身      }      rslt = f.delete();//删除此文件夹本身    }

    if(!rslt)      throw new IOException("无法删除:"+f.getName());    return;  }

  public static void main(String[] args) {    DeleteAll da= new DeleteAll();    try {      da.delAll(new File("someDir"));    }    catch (IOException ex) {      ex.printStackTrace();    }  }}

 
原创粉丝点击