Java中使用File类删除文件夹和文件
2024-09-27 06:31:27
删除工具类:
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值的异常信息。
最新文章
- 在mvc里面有htmlhelper方法,在webform里面有什么?
- Reflection和Expression Tree解析泛型集合快速定制特殊格式的Json
- PYTHONPATH 可以跨版本 方便使用 (本文为windows方法)转~
- mysql组合索引顺序参考
- [HIHO1062] 最近公共祖先&#183;一(lca, 并查集, 二分, 神trick)
- [CareerCup] 4.8 Contain Tree 包含树
- 下载Xml文件方法
- UVa673 Parentheses Balance
- 保留关键字 (Transact-SQL)
- group by是什么意思 mysql中
- [Immutable.js] Converting Immutable.js Structures to Javascript and other Immutable Types
- 菜鸟学SSH(十二)——Hibernate与Spring配合生成表结构
- AjaxPro.AjaxMethod 简单应用,
- hdu1754 I Hate It (线段树 更新点的值)
- Python——类与对象,异常处理
- OO第一单元小结
- java Quartz任务调度器
- PYTHON 中 SQL 带参数
- JS 单体内置对象
- 程序猿必备的10款web前端动画插件一