In this post we will see How to Delete Directory in Java. We will use the File.delete() method. But to use this method we need the directory to be empty.
I have an directory “kscodes” and its has following folders and files inside it.
Lets try to delete the directory “kscodes” using File.delete()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
package com.kscodes.sampleproject; import java.io.File; public class DelDirExample { public static void main(String[] args) { File dirToBeDeleted = new File("C:\\kscodes"); boolean deleted = dirToBeDeleted.delete(); if (deleted) { System.out.println("Directory Deleted !!!!"); } else { System.out.println("Could not delete Directory"); } } } |
Output
1 |
Could not delete Directory |
This happened because the directory “kscodes” is not empty.
So to delete any directory using File.delete() we first need to empty the directory.
Lets see an example that recursively deletes all the contents from the kscodes directory and then deletes the directory “kscodes” at the end.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
package com.kscodes.sampleproject; import java.io.File; public class DelDirExample { public static void main(String[] args) { File dirToBeDeleted = new File("C:\\kscodes"); System.out.println("Start !!!!"); deleteDir(dirToBeDeleted); System.out.println("End !!!"); } public static void deleteDir(File fileTobeDeleted) { if (fileTobeDeleted.isDirectory()) { // get all Files and directories for the given path String files[] = fileTobeDeleted.list(); for (String file : files) { File fileDelete = new File(fileTobeDeleted, file); // recursion :: to delete all the inner directories and files deleteDir(fileDelete); } // Once all contents from the directory are deleted ; then delete // the directory fileTobeDeleted.delete(); System.out.println("Directory - " + fileTobeDeleted.getAbsolutePath() + " deleted"); } else { // if not a directory, then directly delete the file. fileTobeDeleted.delete(); System.out.println("File - " + fileTobeDeleted.getAbsolutePath() + " deleted"); } } } |
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
Start !!!! File - C:\kscodes\file1.txt deleted File - C:\kscodes\file2.txt deleted File - C:\kscodes\testDirectoryOne\OneDirFile1.txt deleted File - C:\kscodes\testDirectoryOne\OneDirFile2.txt deleted Directory - C:\kscodes\testDirectoryOne deleted File - C:\kscodes\testDirectoryThree\ThreeDirFile1.txt deleted File - C:\kscodes\testDirectoryThree\ThreeDirFile2.txt deleted File - C:\kscodes\testDirectoryThree\ThreeDirFile3.txt deleted Directory - C:\kscodes\testDirectoryThree deleted File - C:\kscodes\testDirectoryTwo\TwoDirFile1.txt deleted File - C:\kscodes\testDirectoryTwo\TwoDirFile2.txt deleted Directory - C:\kscodes\testDirectoryTwo deleted Directory - C:\kscodes deleted End !!! |