How to delete a folder with files using Java

I want to create and delete a directory using Java, but it does not work.

File index = new File("/home/Work/Indexer1"); if (!index.exists()) { index.mkdir(); } else { index.delete(); if (!index.exists()) { index.mkdir(); } } 
+92
java file-io delete-directory
Nov 29 '13 at 9:04 on
source share
26 answers

Java cannot delete folders with data in it. Before deleting a folder, you must delete all files.

Use something like:

 String[]entries = index.list(); for(String s: entries){ File currentFile = new File(index.getPath(),s); currentFile.delete(); } 

Then you can delete the folder using index.delete() Unverified!

+88
Nov 29 '13 at 9:11
source share

Just one line.

 import org.apache.commons.io.FileUtils; FileUtils.deleteDirectory(new File(destination)); 

Documentation here

+158
May 15 '14 at 12:39
source share

This works, and although it does not look effective to skip the directory test, it doesnโ€™t: the test happens immediately in listFiles() .

 void deleteDir(File file) { File[] contents = file.listFiles(); if (contents != null) { for (File f : contents) { deleteDir(f); } } file.delete(); } 

Update to avoid the following symbolic links:

 void deleteDir(File file) { File[] contents = file.listFiles(); if (contents != null) { for (File f : contents) { if (! Files.isSymbolicLink(f.toPath())) { deleteDir(f); } } } file.delete(); } 
+91
Mar 20 '15 at 20:22
source share

In JDK 7, you can use Files.walkFileTree() and Files.deleteIfExists() to delete the file tree.

In JDK 6, one possible way is to use FileUtils.deleteQuietly from Apache Commons, which will delete a file, directory, or directory with files and subdirectories.

+23
Nov 29 '13 at 9:13
source share

Using Apache Commons-IO, it looks like this:

 import org.apache.commons.io.FileUtils; FileUtils.forceDelete(new File(destination)); 

This is (slightly) more productive than FileUtils.deleteDirectory .

+19
Jan 13 '15 at
source share

I prefer this solution in Java 8:

  Files.walk(pathToBeDeleted) .sorted(Comparator.reverseOrder()) .map(Path::toFile) .forEach(File::delete); 

From this site: http://www.baeldung.com/java-delete-directory

+19
Oct 27 '17 at 20:39 on
source share

My basic recursive version working with older versions of the JDK:

 public static void deleteFile(File element) { if (element.isDirectory()) { for (File sub : element.listFiles()) { deleteFile(sub); } } element.delete(); } 
+9
Mar 24 '15 at 10:21
source share

This is the best solution for Java 7+ :

 public static void deleteDirectory(String directoryFilePath) throws IOException { Path directory = Paths.get(directoryFilePath); if (Files.exists(directory)) { Files.walkFileTree(directory, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path path, BasicFileAttributes basicFileAttributes) throws IOException { Files.delete(path); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path directory, IOException ioException) throws IOException { Files.delete(directory); return FileVisitResult.CONTINUE; } }); } } 
+8
Feb 21 '17 at 16:30
source share

As already mentioned, Java cannot delete the folder containing the files, so first delete the files and then the folder.

Here is a simple example to do this:

 import org.apache.commons.io.FileUtils; // First, remove files from into the folder FileUtils.cleanDirectory(folder/path); // Then, remove the folder FileUtils.deleteDirectory(folder/path); 

Or:

 FileUtils.forceDelete(new File(destination)); 
+6
May 15 '19 at 10:02
source share

Guava 21+ to the rescue. Use only if there are no symbolic links pointing to the directory to be deleted.

 com.google.common.io.MoreFiles.deleteRecursively( file.toPath(), RecursiveDeleteOption.ALLOW_INSECURE ) ; 

(This question is well indexed by Google, so other Usig Guava users may love to find this answer, even if it is redundant with other answers elsewhere.)

+5
Aug 04 '17 at 8:08 on
source share

I like this solution the most. It does not use a third-party library; instead, it uses NIO2 Java 7.

 /** * Deletes Folder with all of its content * * @param folder path to folder which should be deleted */ public static void deleteFolderAndItsContent(final Path folder) throws IOException { Files.walkFileTree(folder, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { if (exc != null) { throw exc; } Files.delete(dir); return FileVisitResult.CONTINUE; } }); } 
+4
Mar 31 '16 at 10:30
source share

In that

 index.delete(); if (!index.exists()) { index.mkdir(); } 

you call

  if (!index.exists()) { index.mkdir(); } 

after

 index.delete(); 

This means that you create the file again after deletion. File.delete () returns a boolean value. Therefore, if you want to check, then do System.out.println(index.delete()); if you get true then it means this file is deleted

 File index = new File("/home/Work/Indexer1");  if (!index.exists())    {       index.mkdir();    }  else{      System.out.println(index.delete());//If you get true then file is deleted      if (!index.exists())        {          index.mkdir();// here you are creating again after deleting the file        }    } 

from the comments below, the updated answer is as follows

 File f=new File("full_path");//full path like c:/home/ri if(f.exists()) { f.delete(); } else { try { //f.createNewFile();//this will create a file f.mkdir();//this create a folder } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } 
+2
Nov 29 '13 at 9:09
source share

You can use FileUtils.deleteDirectory . JAVA cannot delete non-empty folds with File.delete () .

+2
Jan 03 '19 at 16:58
source share

directry cannot just delete if it has files, so you may need to delete the files inside first and then the directory

 public class DeleteFileFolder { public DeleteFileFolder(String path) { File file = new File(path); if(file.exists()) { do{ delete(file); }while(file.exists()); }else { System.out.println("File or Folder not found : "+path); } } private void delete(File file) { if(file.isDirectory()) { String fileList[] = file.list(); if(fileList.length == 0) { System.out.println("Deleting Directory : "+file.getPath()); file.delete(); }else { int size = fileList.length; for(int i = 0 ; i < size ; i++) { String fileName = fileList[i]; System.out.println("File path : "+file.getPath()+" and name :"+fileName); String fullPath = file.getPath()+"/"+fileName; File fileOrFolder = new File(fullPath); System.out.println("Full Path :"+fileOrFolder.getPath()); delete(fileOrFolder); } } }else { System.out.println("Deleting file : "+file.getPath()); file.delete(); } } 
+1
Nov 29 '13 at 9:13
source share

If you have subfolders, you will find problems with Cemron's answers. therefore, you must create a method that works as follows:

 private void deleteTempFile(File tempFile) { try { if(tempFile.isDirectory()){ File[] entries = tempFile.listFiles(); for(File currentFile: entries){ deleteTempFile(currentFile); } tempFile.delete(); }else{ tempFile.delete(); } getLogger().info("DELETED Temporal File: " + tempFile.getPath()); } catch(Throwable t) { getLogger().error("Could not DELETE file: " + tempFile.getPath(), t); } } 
+1
Mar 21 '14 at 15:17
source share

You can make a recursive call if subdirectories exist

 import java.io.File; class DeleteDir { public static void main(String args[]) { deleteDirectory(new File(args[0])); } static public boolean deleteDirectory(File path) { if( path.exists() ) { File[] files = path.listFiles(); for(int i=0; i<files.length; i++) { if(files[i].isDirectory()) { deleteDirectory(files[i]); } else { files[i].delete(); } } } return( path.delete() ); } } 
+1
Mar 07 '17 at 6:07
source share

we can use the spring-core dependency;

 boolean result = FileSystemUtils.deleteRecursively(file); 
+1
Jul 01 '18 at 10:41
source share

Most answers (even recent ones) that reference JDK classes are based on File.delete() but this is not a File.delete() API, as the operation may fail.
The java.io.File.delete() method documentation says:

Note that the java.nio.file.Files class defines the delete method to create delete IOException when the file cannot be deleted. This is useful for reporting errors and for diagnosing why a file cannot be deleted.

As a replacement, you should Files.delete(Path p) preference Files.delete(Path p) which throws an IOException with an error message.

Actual code can be written like this:

 Path index = Paths.get("/home/Work/Indexer1"); if (!Files.exists(index)) { index = Files.createDirectories(index); } else { Files.walk(index) .sorted(Comparator.reverseOrder()) // as the file tree is traversed depth-first and that deleted dirs have to be empty .forEach(t -> { try { Files.delete(t); } catch (IOException e) { // LOG the exception and potentially stop the processing } }); if (!Files.exists(index)) { index = Files.createDirectories(index); } } 
+1
Jul 13 '18 at 2:59
source share

you can try the following

  File dir = new File("path"); if (dir.isDirectory()) { dir.delete(); } 

If your folder has subfolders, you may need to delete them recursively.

0
Nov 29 '13 at 9:10
source share
 private void deleteFileOrFolder(File file){ try { for (File f : file.listFiles()) { f.delete(); deleteFileOrFolder(f); } } catch (Exception e) { e.printStackTrace(System.err); } } 
0
Jan 01 '15 at 22:04
source share
  import org.apache.commons.io.FileUtils; List<String> directory = new ArrayList(); directory.add("test-output"); directory.add("Reports/executions"); directory.add("Reports/index.html"); directory.add("Reports/report.properties"); for(int count = 0 ; count < directory.size() ; count ++) { String destination = directory.get(count); deleteDirectory(destination); } public void deleteDirectory(String path) { File file = new File(path); if(file.isDirectory()){ System.out.println("Deleting Directory :" + path); try { FileUtils.deleteDirectory(new File(path)); //deletes the whole folder } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { System.out.println("Deleting File :" + path); //it is a simple file. Proceed for deletion file.delete(); } } 

Works like a charm. For folders and files. Salam :)

0
Jan 26 '16 at 10:45
source share

Remove it from another part

 File index = new File("/home/Work/Indexer1"); if (!index.exists()) { index.mkdir(); System.out.println("Dir Not present. Creating new one!"); } index.delete(); System.out.println("File deleted successfully"); 
-one
Nov 29 '13 at 9:08
source share

Some of these answers seem unnecessarily long:

 if (directory.exists()) { for (File file : directory.listFiles()) { file.delete(); } directory.delete(); } 

It works for subdirectories.

-one
Sep 18 '17 at 9:48 on
source share
 import java.io.File; public class Main{ public static void main(String[] args) throws Exception { deleteDir(new File("c:\\temp")); } 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(); System.out.println("The directory is deleted."); } } 
-one
Jan 18 '19 at 5:41
source share

Create Directory -

 File directory = new File("D:/Java/Example"); boolean isCreated = directory.mkdir(); 

Delete Directory -

For more details see this resource - delete directory .

-2
Dec 20 '17 at 12:27
source share

You can use this function

 public void delete() { File f = new File("E://implementation1/"); File[] files = f.listFiles(); for (File file : files) { file.delete(); } } 
-3
Mar 21 '16 at 18:20
source share



All Articles