用递归方式来实现删除硬盘的文件或目录(空文件夹)
首先要找到递归的入口及出口,这点很重要,成败在此,呵呵!
代码实现:
- import java.io.File ;
-
- class RecursionDeleteFileDemo
- {
- public static void deleteFiles(File file)
- {
-
-
- if(file.isFile() || file.list().length == 0)
- {
- file.delete() ;
- }
- else
- {
- File[] files = file.listFiles() ;
- for(File f : files)
- {
-
- deleteFiles(f) ;
- f.delete() ;
- }
-
- }
- }
- }
-
- public class RecursionDeleteFile
- {
- public static void main(String[] args)
- {
- File file = new File("E:/abc") ;
-
- RecursionDeleteFileDemo.deleteFiles (file) ;
-
-
- }
- }
File[] files = file.listFiles() ;
返回: 抽象路径名数组,这些路径名表示此抽象路径名表示的目录中的文件和目录
测试类程序:RecursionDeleteFileDemoTest.java
- package com.junit3_8;
-
- import java.io.File;
- import java.io.IOException;
-
- import junit.framework.Assert;
- import junit.framework.TestCase;
-
- public class RecursionDeleteFileDemoTest extends TestCase{
-
-
- public void testDeleteFiles()
- {
-
- File file = null ;
- try {
-
- file = new File("a.txt");
- file.createNewFile();
- RecursionDeleteFileDemo.deleteFiles(file);
-
-
- } catch (IOException e) {
-
- Assert.fail();
-
- }
-
- boolean result ;
-
- result = file.exists();
- Assert.assertFalse(result);
- }
-
-
-
- public void testDeleteFiles2()
- {
- File directory = null ;
-
- try {
-
- directory = new File("root");
- directory.mkdir();
-
- File file0 = new File(directory,"xx.txt");
- file0.createNewFile();
-
-
- File file1 = new File(directory,"child1");
- File file2 = new File(directory,"child2");
- file1.mkdir();
- file2.mkdir();
-
-
- File file3 = new File(file1,"a.txt");
- File file4 = new File(file2,"b.txt");
- file3.createNewFile();
- file4.createNewFile();
-
- RecursionDeleteFileDemo.deleteFiles(directory);
-
-
-
-
- }
- catch(Exception e)
- {
- Assert.fail();
- }
-
- Assert.assertNotNull(directory);
- String[] str = directory.list();
- Assert.assertEquals(0, str.length);
- directory.delete();
-
- }
-
-
- }
JUnit 3.8 演示递归删除文件目录的 测试类程序 .
原文:http://www.cnblogs.com/hoobey/p/5293994.html