程序员社区

Java IO教程 --- 使用递归删除目录/文件夹

前面我们学习了如何在 java 中创建文件以及如何在 java中删除文件。在这里我们将学习如何在java中递归删除一个非空目录/文件夹。

Java 删除目录

Java Filedelete()方法删除文件或空目录。但是,如果目录不为空,则不会删除它并返回 false。

我们将递归地使用 delete() 函数来删除 java 程序中的目录/文件夹。

package com.journaldev.files;

import java.io.File;

/**
 * This utility class can be used to delete 
 * folders recursively in java
 * @author pankaj
 */
public class DeleteFolderRecursively {

    public static void main(String[] args) {
        String folder = "/Users/pankaj/tmp";
        //delete folder recursively
        recursiveDelete(new File(folder));
    }

    public static void recursiveDelete(File file) {
        //to end the recursive loop
        if (!file.exists())
            return;

        //if directory, go inside and call recursively
        if (file.isDirectory()) {
            for (File f : file.listFiles()) {
                //call recursively
                recursiveDelete(f);
            }
        }
        //call delete to delete files and empty directory
        file.delete();
        System.out.println("Deleted file/folder: "+file.getAbsolutePath());
    }

}

在这里,我们使用 delete() 删除文件夹内容,如果是目录,则递归调用recursiveDelete方法。

这是上面删除目录的程序的输出。

Deleted file/folder: /Users/pankaj/tmp/.DS_Store
Deleted file/folder: /Users/pankaj/tmp/data/data.dat
Deleted file/folder: /Users/pankaj/tmp/data/data.sql
Deleted file/folder: /Users/pankaj/tmp/data
Deleted file/folder: /Users/pankaj/tmp/DB.xml
Deleted file/folder: /Users/pankaj/tmp/item.xsd
Deleted file/folder: /Users/pankaj/tmp/ms/data.txt
Deleted file/folder: /Users/pankaj/tmp/ms/project.doc
Deleted file/folder: /Users/pankaj/tmp/ms
Deleted file/folder: /Users/pankaj/tmp

您可以使用此实用程序方法删除非空目录。

赞(0) 打赏
未经允许不得转载:IDEA激活码 » Java IO教程 --- 使用递归删除目录/文件夹

一个分享Java & Python知识的社区