如何使用递归删除Java中的目录/文件夹

时间:2020-02-23 14:34:26  来源:igfitidea点击:

之前我们学习了如何在Java中创建文件以及如何在Java中删除文件。
其中我们将学习如何递归地删除Java中的非空目录/文件夹。

Java删除目录

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

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

package com.theitroad.files;

import java.io.File;

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

  public static void main(String[] args) {
      String folder = "/Users/hyman/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/hyman/tmp/.DS_Store
Deleted file/folder: /Users/hyman/tmp/data/data.dat
Deleted file/folder: /Users/hyman/tmp/data/data.sql
Deleted file/folder: /Users/hyman/tmp/data
Deleted file/folder: /Users/hyman/tmp/DB.xml
Deleted file/folder: /Users/hyman/tmp/item.xsd
Deleted file/folder: /Users/hyman/tmp/ms/data.txt
Deleted file/folder: /Users/hyman/tmp/ms/project.doc
Deleted file/folder: /Users/hyman/tmp/ms
Deleted file/folder: /Users/hyman/tmp