devxlogo

Recursively Delete Directories in Java

Recursively Delete Directories in Java

In Java, a readable, writable directory should be empty before an attempt is made to remove it. The following code recursively empties a directory, and its sub-directories, and then removes them.

 private void deleteFile(File p_file) { String FILE_SEPARATOR = System.getProperty("file.separator"); // If it is a directory, empty it first System.out.println("Deleting: "+p_file.getPath()); if(p_file.isDirectory()) { String[] dirList = p_file.list(); for(int i=0; i

Note that a File object should be writable by the current user of the code in order to be removed.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist