如下程序:
- import java.io.File;
- public class DeleteAll{
- public static void deleteAll(File file){
- if(file.isFile() || file.list().length ==0)
- {
- file.delete();
- }else{
- File[] files = file.listFiles();
- for (int i = 0; i < files.length; i++) {
- deleteAll(files[i]);
- files[i].delete();
- }
- if(file.exists()) //如果文件本身就是目录 ,就要删除目录
- file.delete();
- }
- }
- public static void main(String[] args){
- File f = new File("f:"+File.separator+"test");
- deleteAll(f);
- }
- }
请不要轻易测试! 我的单元测试如下:
- package com.jzm;
- import java.io.File;
- import junit.framework.Assert;
- import junit.framework.TestCase;
- public class DeleteAllTest extends TestCase{
- public void testDeleteAll(){ //如果是一个文件
- File file = null;
- try{
- file = new File("f:\\test\\a.txt");
- file.createNewFile();
- DeleteAll.deleteAll(file);
- }catch (Exception e) {
- // TODO: handle exception
- }
- Assert.assertFalse(file.exists());
- }
- public void testDeleteAll2(){ //如果是一个一级目录
- File directory = null;
- try{
- directory = new File("f:"+ File.separator +"dirT2");
- directory.mkdir();
- File file1 = new File(directory, "t1.txt");
- File file2 = new File(directory, "t2.txt");
- file1.createNewFile();
- file2.createNewFile();
- DeleteAll.deleteAll(directory);
- }catch (Exception e) {
- // TODO: handle exception
- }
- Assert.assertFalse(directory.exists());
- }
- public void testDeleteAll3(){ //如果是一个二级目录
- File directory = null;
- try{
- directory = new File("f:"+ File.separator +"dirT3");
- directory.mkdir();
- File dir1 = new File(directory,"dir1");
- dir1.mkdir();
- File dir2 = new File(directory,"dir2");
- dir2.mkdir();
- File file1 = new File(dir1, "t1.txt");
- File file2 = new File(dir2, "t2.txt");
- file1.createNewFile();
- file2.createNewFile();
- DeleteAll.deleteAll(directory);
- }catch (Exception e) {
- // TODO: handle exception
- }
- Assert.assertFalse(directory.exists());
- }
- }