How to delete a folder with files using Java

后端 未结 28 3029
北荒
北荒 2020-11-28 05:36

I want to create and delete a directory using Java, but it isn\'t working.

File index = new File(\"/home/Work/Indexer1\");
if (!index.exists()) {
    index.m         


        
相关标签:
28条回答
  • 2020-11-28 05:49

    In JDK 7 you could use Files.walkFileTree() and Files.deleteIfExists() to delete a tree of files. (Sample: http://fahdshariff.blogspot.ru/2011/08/java-7-deleting-directory-by-walking.html)

    In JDK 6 one possible way is to use FileUtils.deleteQuietly from Apache Commons which will remove a file, a directory, or a directory with files and sub-directories.

    0 讨论(0)
  • 2020-11-28 05:50

    I prefer this solution on java 8:

      Files.walk(pathToBeDeleted)
        .sorted(Comparator.reverseOrder())
        .map(Path::toFile)
        .forEach(File::delete);
    

    From this site: http://www.baeldung.com/java-delete-directory

    0 讨论(0)
  • 2020-11-28 05:50

    Guava 21+ to the rescue. Use only if there are no symlinks pointing out of the directory to delete.

    com.google.common.io.MoreFiles.deleteRecursively(
          file.toPath(),
          RecursiveDeleteOption.ALLOW_INSECURE
    ) ;
    

    (This question is well-indexed by Google, so other people usig Guava might be happy to find this answer, even if it is redundant with other answers elsewhere.)

    0 讨论(0)
  • 2020-11-28 05:55

    You can make recursive call if sub directories exists

    import java.io.File;
    
    class DeleteDir {
    public static void main(String args[]) {
    deleteDirectory(new File(args[0]));
    }
    
    static public boolean deleteDirectory(File path) {
    if( path.exists() ) {
      File[] files = path.listFiles();
      for(int i=0; i<files.length; i++) {
         if(files[i].isDirectory()) {
           deleteDirectory(files[i]);
         }
         else {
           files[i].delete();
         }
      }
    }
    return( path.delete() );
    }
    }
    
    0 讨论(0)
  • 2020-11-28 05:55

    Some of these answers seem unnecessarily long:

    if (directory.exists()) {
        for (File file : directory.listFiles()) {
            file.delete();
        }
        directory.delete();
    }
    

    Works for sub directories too.

    0 讨论(0)
  • 2020-11-28 05:56

    My basic recursive version, working with older versions of JDK:

    public static void deleteFile(File element) {
        if (element.isDirectory()) {
            for (File sub : element.listFiles()) {
                deleteFile(sub);
            }
        }
        element.delete();
    }
    
    0 讨论(0)
提交回复
热议问题