java使用递归删除非空目录

使用递归删除非空目录

目录的创建: file.makdir();

空目录的删除: file.delete();

例一、

package file;

import java.io.File;

public class Filetext {

    public static void main(String[] args) {
        show(new File("D:/999"));
    }
    public static void show(File file) {
        if(file.isDirectory()) {
            File[] f = file.listFiles();
            for(File name : f) {
                if(name.isFile()) {
                   name.delete();
                }show(name);                
            }        
        }file.delete();        
    }
}

例二、

package day05;
import java.io.File;
public class Work02 {   
    public static void main(String[] args) {
        // 使用递归删除非空目录
           deleteFile(new File("c:/abc"));          
    }    
    public static void deleteFile(File file) {
        if(file.isFile()) {
            file.delete();
        }else {
            String[] childFilePaths = file.list();//得到当前的路径
            for(String childFilePath : childFilePaths) {
                File childFile = new File(file.getAbsolutePath() + "\" + childFilePath);//?
                deleteFile(childFile);
            }
            file.delete();
        }
    }
}
原文地址:https://www.cnblogs.com/zxwen/p/9460902.html