删除工具类:
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);
}
}
单元测试Junit:
(注意:Assert.assertFalse(cond):判断参数cond是否为false,如该值为true,则抛出含有参数message值的异常信息)
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
}
//判断是否为false
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());
}
}
关于Assert:
Assert.Fail () 在不检查任何条件的情况下使断言失败。
Assert.Fail (String) 在不检查任何条件的情况下使断言失败。显示消息。
Assert.Fail (String, Object[]) 在不检查任何条件的情况下使断言失败。显示一则消息,并向该消息应用指定的格式。
Assert.Fail (String): 运行到该句时,直接使该断言失败,并且将括号中的String参数直接显示出来;
Assert.assertFalse(java.lang.String message,boolean condition):
判断参数condition是否为false,假如该参数值为true,则抛出含有参数message值的异常信息。
http://blog.csdn.net/love_ubuntu/article/details/6673722
http://kang.iteye.com/blog/568991