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();
}
}
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(); } }} |