How to delete a folder with files using Java?

Java isn’t able to delete folders with data in it. You have to delete all files before deleting the folder.

Delete a non-empty directories recursively in Java

 

  • How do you delete entire directories with contents in Java With recursive method.
package com.nourit.javaIO;

import java.io.File;

public class DeleteDirectoryANDFiles {

  public static void main(String args[]) {
    System.out.println("!!!!! Java isn’t able to delete folders with data in it        !!!!");
    System.out.println("!!!!! You have to delete all files before deleting the folder  !!!!");
    System.out.println("!!!!! -------------------------------------------------------- !!!!");
    DeleteDirectoryANDFiles.deleteDirectoryOrFiles(new File("D:/tmp/nourit"));
  }

  static public boolean deleteDirectoryOrFiles(File path) {
    if (path.exists()) {
      File[] files = path.listFiles();
      for (int i = 0; i < files.length; i++) {
        if (files[i].isDirectory()) {
          deleteDirectoryOrFiles(files[i]);
        } else {
          System.out.println("here ist a File: " + files[i].getAbsolutePath() + ", deleted... ");
          files[i].delete();
        }
      }
    }
    boolean isDeleted = path.delete();
    if(isDeleted){
      System.out.println("here ist a Directory: " + path.getName() + ", is deleted now... ");
    }
    return isDeleted;
  }
}

Output:

!!!!! Java isn’t able to delete folders with data in it        !!!!
!!!!! You have to delete all files before deleting the folder  !!!!
!!!!! -------------------------------------------------------- !!!!
here ist a File: D:\tmp\nourit\nourit-test-1.txt, deleted... 
here ist a File: D:\tmp\nourit\nourit-test-2.txt, deleted... 
here ist a File: D:\tmp\nourit\nourit-test-3.txt, deleted... 
here ist a Directory: nourit, is deleted now...

 

NOUR-IT

IT Training Center for Java and Web technology. If you enjoy and like our tutorials and believe in our mission, Please Subscribe us on Youtube and follow us on Twitter, or befriend us on Facebook or Google Plus.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.

*