Create a directory. If exists, delete the directory and its contents and create a new one in Java

I am trying to create a directory in Java. If it exists, I want to delete this directory and its contents and create a new one. I am trying to do the following, but the directory is not deleted. New files are added to the directory.

File file = new File("path"); boolean isDirectoryCreated = file.mkdir(); if (isDirectoryCreated) { System.out.println("successfully made"); } else { file.delete(); file.mkdir(); System.out.println("deleted and made"); } 

I create this directory at runtime in the directory of a running project. After each launch, the old content must be deleted, and the new content must be present in this directory.

+6
source share
3 answers
 public static boolean deleteDir(File dir) { if (dir.isDirectory()) { String[] children = dir.list(); for (int i=0; i<children.length; i++) { boolean success = deleteDir(new File(dir, children[i])); if (!success) { return false; } } } return dir.delete(); } 
+8
source

Thanks to Apache, it is very simple.

 import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; public class DeleteFolder { public static void main(String[] args){ try { File f = new File("/var/www/html/testFolder1"); FileUtils.cleanDirectory(f); //clean out directory (this is optional -- but good know) FileUtils.forceDelete(f); //delete directory FileUtils.forceMkdir(f); //create directory } catch (IOException e) { e.printStackTrace(); } } } 
+7
source

You need to first delete the contents of the directory, but only delete the directory. You can try something like this: -

 File file = new File("path"); boolean isDirectoryCreated = file.mkdir(); if (isDirectoryCreated) { System.out.println("successfully made"); } else { deleteDir(file); // Invoke recursive method file.mkdir(); } public void deleteDir(File dir) { File[] files = dir.listFiles(); for (File myFile: files) { if (myFile.isDirectory()) { deleteDir(myFile); } myFile.delete(); } } 
+5
source

Source: https://habr.com/ru/post/927434/


All Articles