Tuesday 28 June 2016

How to Delete a Directory/Folder in Java using Recursion


package com.java.io;

import java.io.File;

/** To delete folders recursively. */
public class DeleteDirectory {

     public static void main(String[] args) {
           String folder = "C:/temp/Dir";

           /** delete directory recursively */
           recurDelete(new File(folder));
     }

     public static void recurDelete(File file) {
           /** recursive loop termination. */
           if (!file.exists()) {
                return;
           }

           /** if directory, go inside and call recursively */
           if (file.isDirectory()) {
                for (File tFile : file.listFiles()) {
                     /** recursive call */
                     recurDelete(tFile);
                }
           }
          
           /** To delete files and empty directory */
           boolean isFileDeleted = file.delete();

           if(isFileDeleted) {
                System.out.println("File deleted: "+file.getAbsolutePath());
           }
     }
}

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...