We are moved to new domain
Click -> www.ehowtonow.com
Wednesday, 24 May 2017

How to delete directory using Java

boolean java.io.File.delete()

Deletes the file or directory denoted by this abstract pathname. If this pathname denotes a directory, then the directory must be empty in order to be deleted.

Note that the java.nio.file.Files class defines the delete method to throw an IOException when a file cannot be deleted. This is useful for error reporting and to diagnose why a file cannot be deleted.

Returns:
true if and only if the file or directory is successfully deleted; false otherwise

Throws:
SecurityException - If a security manager exists and its java.lang.SecurityManager.checkDelete method denies delete access to the file

DeleteDirectory.java
package com.javatutorialcorner.directory;

import java.io.File;

public class DeleteDirectory {

 public static void main(String[] args) {
  File directory = new File("C:/JTC/");
  boolean isDeleted =  directory.delete();
  System.out.println("Is Directory Deleted "+isDeleted);
  isDeleted =  deleteDirectory(directory);
  System.out.println("Is Directory Deleted "+isDeleted);
  
 }

  public static boolean deleteDirectory(File dir) {
       if (dir.isDirectory()) {
          String[] children = dir.list();
          for (int i = 0; i < children.length; i++) {
             boolean success = deleteDirectory (new File(dir, children[i]));
             
             if (!success) {
                return false;
             }
          }
       }
       return dir.delete();
    }
}
Output
Is Directory Deleted false
Is Directory Deleted true

Shop and help us

Flipkart Offer Snapdeal offer Amazon.in offer Amazon.com offer
  • Blogger Comments
  • Facebook Comments
  • Disqus Comments

0 comments:

Post a Comment

Item Reviewed: How to delete directory using Java Rating: 5 Reviewed By: eHowToNow