Java File IO - Clean and Remove a non-empty directory
- Details
- Written by Nam Ha Minh
- Last Updated on 27 July 2019   |   Print Email
This Java File IO tutorial helps you write code to delete all files and sub directories and sub files in a given directory.
In Java, to remove a directory we can call delete() method on a File object, for example:
String dirPath = "D:/Dir/To/Remove"; File dir = new File(dirPath); try { boolean deleted = dir.delete(); if (deleted) { System.out.println("Directory removed."); } else { System.out.println("Directory could not be removed"); } } catch (SecurityException ex) { System.out.println("Delete is denied."); }
However the delete() method is only working with an empty directory. What if the directory is not empty and contains several sub files and directories? Well, in that case, we have to iterate over all of the sub files/sub directories, delete every file in a sub directory until the directory becomes empty, and then delete the sub directory itself. And that involves in some sort of recursion algorithm.
Remove a non empty directory example:
The following static method:
- Recursively deletes sub files and sub directories.
- Delete the main directory.
public static void removeDirectory(File dir) { if (dir.isDirectory()) { File[] files = dir.listFiles(); if (files != null && files.length > 0) { for (File aFile : files) { removeDirectory(aFile); } } dir.delete(); } else { dir.delete(); } }
Clean a non empty directory example:
Clean a directory does not delete the main directory but all sub files and directories, results in the main directory being empty:
public static void cleanDirectory(File dir) { if (dir.isDirectory()) { File[] files = dir.listFiles(); if (files != null && files.length > 0) { for (File aFile : files) { removeDirectory(aFile); } } } }
Note that the cleanDirectory() method re-uses the removeDirectory() method.
You can download the demo program in the attachment section.
Related File IO Tutorials:
- Calculate total files, sub directories and size of a directory
- How to copy a directory programmatically in Java
- List files and directories recursively in a directory in Java
- How to rename/move file or directory in Java
Other Java File IO Tutorials:
- How to Read and Write Text File in Java
- How to Read and Write Binary Files in Java
- Java IO - Common File and Directory Operations Examples
- Java Serialization Basic Example
- Understanding Java Externalization with Examples
- How to compress files in ZIP format in Java
- How to extract ZIP file in Java
Comments
I think no. the if clause is for a directory and the else clause is for a file.
In removeDirectory method do we need dir.delete() in two places, in both if and else block. It can be moved as last statement of the method, outside if.