Java-删除文件夹

Java-删除文件夹

Tags: Java

摘要

Java-删除文件夹

Java删除文件夹

删除文件夹,可以简单的使用File.delete(),但是要求目录为空才能删除。所以通常情况下需要递归删除文件夹,也就是要先删除文件夹下所有的子文件夹和文件,然后才能删除指定的文件夹。

删除文件夹例子

package cn.javacore.io.directory;

import java.io.File;
import java.io.IOException;

public class _02_DeleteDirectoryExample {

    private static final String SRC_FOLDER = "/home/zhu/javacore.cn/Directory2";

    public static void main(String[] args) {

        File directory = new File(SRC_FOLDER);

        //make sure directory exists
        if (!directory.exists()) {
            System.out.println("Directory does not exist.");
            System.exit(0);
        } else {
            try {
                delete(directory);
            } catch (IOException e) {
                e.printStackTrace();
                System.exit(0);
            }
        }

        System.out.println("Done");
    }

    public static void delete(File file)
            throws IOException {

        if (file.isDirectory()) {

            //directory is empty, then delete it
            if (file.list().length == 0) {
                file.delete();
                System.out.println("Directory is deleted : "
                        + file.getAbsolutePath());
            } else {
                //list all the directory contents
                String files[] = file.list();
                for (String temp : files) {
                    //construct the file structure
                    File fileDelete = new File(file, temp);
                    //recursive delete
                    delete(fileDelete);
                }
                //check the directory again, if empty then delete it
                if (file.list().length == 0) {
                    file.delete();
                    System.out.println("Directory is deleted : "
                            + file.getAbsolutePath());
                }
            }
        } else {
            //if file, then delete it
            file.delete();
            System.out.println("File is deleted : " + file.getAbsolutePath());
        }
    }
}

删除结果

File is deleted : /home/zhu/javacore.cn/Directory2/ABC.log
Directory is deleted : /home/zhu/javacore.cn/Directory2/Sub2/Sub-Sub2
Directory is deleted : /home/zhu/javacore.cn/Directory2/Sub2
Directory is deleted : /home/zhu/javacore.cn/Directory2
Done