Sunday, March 6, 2022

Java Program to Delete File And Directory Recursively

Methods given in Java for deleting a directory work only when the directory is empty, in case you want to recursively delete a directory then you need to write logic to walk through the whole folder structure (files and sub-folders) to delete all of them before deleting the parent directory. This article shows how can you delete a file or directory in Java and how to recursively delete a directory in Java.


Methods in Java for deleting file or directory

  1. delete()- In java.io.File class there is a delete() method which deletes the file or directory denoted by this abstract pathname. If this pathname denotes a directory, then the directory must be empty in order to be deleted. Method retruns true if the file or directory is successfully deleted; false otherwise.
  2. Files.delete(Path path)- java.nio.file.Files.delete() method available Java 7 onward is another option for deleting a file in Java. If the file is a directory then the directory must be empty in order to be deleted. Throws NoSuchFileException if the file does not exist, throws DirectoryNotEmptyException if the file is a directory and could not otherwise be deleted because the directory is not empty.
  3. deleteIfExists(Path path)- java.nio.file.Files.deleteIfExists() method available Java 7 onward deletes a file if it exists. If the file is a directory then the directory must be empty. Throws DirectoryNotEmptyException if the file is a directory and could not otherwise be deleted because the directory is not empty.

java.io.File delete() method example to delete file

import java.io.File;

public class DeleteFileExp {

 public static void main(String[] args) {
  File file = new File("F:\\Temp\\abc.txt");
  deleteFile(file);
         
  // deleting file that doesn't exist scenario
  file = new File("F:\\Temp\\xyz.txt");
  deleteFile(file);
  
  // Deleting empty directory scenario
  file = new File("F:\\NETJS\\EmptyDir");
  deleteFile(file);
  
  // Deleting non-empty directory scenario
  file = new File("F:\\Temp");
  deleteFile(file);
 }
 
  private static void deleteFile(File file){
    if(file.delete()){
      System.out.println("File " + file.getName() + " deleted");
    }else{
      System.out.println("File " + file.getName() + " not deleted, reason file doesn't exist or non-empty directory");
    }
  }
}

Output

File abc.txt deleted
File xyz.txt not deleted, reason file doesn't exist or non-empty directory
File EmptyDir deleted
File Temp not deleted, reason file doesn't exist or non-empty directory

Files.delete() method example to delete file/directory

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class DeleteFileExp {

 public static void main(String[] args) throws IOException {
  // deleting file
  Files.delete(Paths.get("F:\\Temp\\abc.txt"));
         
  // Deleting empty directory scenario
  Files.delete(Paths.get("F:\\NETJS\\EmptyDir"));
 }
}

When the file doesn’t exist or non-empty directory deletion scenario with Files.delete() method.

public class DeleteFileExp {

 public static void main(String[] args) throws IOException {
  // deleting file
  Files.delete(Paths.get("F:\\Temp\\abc.txt"));
         
  //Deleting empty directory scenario
  //Files.delete(Paths.get("F:\\Temp"));
 }
}

Output

Exception in thread "main" java.nio.file.NoSuchFileException: F:\Temp\abc.txt
 at java.base/sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:85)
 at java.base/sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:103)
 at java.base/sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:108)
 at java.base/sun.nio.fs.WindowsFileSystemProvider.implDelete(WindowsFileSystemProvider.java:274)
 at java.base/sun.nio.fs.AbstractFileSystemProvider.delete(AbstractFileSystemProvider.java:105)
 at java.base/java.nio.file.Files.delete(Files.java:1144)
 at org.netjs.prog.DeleteFileExp.main(DeleteFileExp.java:11) 
public class DeleteFileExp {

 public static void main(String[] args) throws IOException {
  // deleting file
  //  Files.delete(Paths.get("F:\\Temp\\abc.txt"));
         
  // Deleting empty directory scenario
  Files.delete(Paths.get("F:\\Temp"));
 }
}

Output

Exception in thread "main" java.nio.file.DirectoryNotEmptyException: F:\Temp
 at java.base/sun.nio.fs.WindowsFileSystemProvider.implDelete(WindowsFileSystemProvider.java:271)
 at java.base/sun.nio.fs.AbstractFileSystemProvider.delete(AbstractFileSystemProvider.java:105)
 at java.base/java.nio.file.Files.delete(Files.java:1144)
 at org.netjs.prog.DeleteFileExp.main(DeleteFileExp.java:14)

Files.deleteIfExists() method example to delete file/directory

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class DeleteFileExp {

 public static void main(String[] args) throws IOException {
  // deleting file
  if(Files.deleteIfExists(Paths.get("F:\\Temp\\abc.txt"))) {
   System.out.println("File deleted successfully");
  }else {
   System.out.println("File not deleted");
  }
         
  // Deleting empty directory scenario
  Files.deleteIfExists(Paths.get("F:\\Temp"));
 }
}

Output

File deleted successfully
Exception in thread "main" java.nio.file.DirectoryNotEmptyException: F:\Temp
 at java.base/sun.nio.fs.WindowsFileSystemProvider.implDelete(WindowsFileSystemProvider.java:271)
 at java.base/sun.nio.fs.AbstractFileSystemProvider.deleteIfExists(AbstractFileSystemProvider.java:110)
 at java.base/java.nio.file.Files.deleteIfExists(Files.java:1183)
 at org.netjs.prog.DeleteFileExp.main(DeleteFileExp.java:18) 

As you can see exception is thrown when there is an attempt to delete a non-empty directory.

Deleting directory recursively in Java

In all the above examples trying to delete a non-empty directory results in an exception being thrown. In case of non-empty directory you need to walk through the directory structure and delete all the files and sub-directories with in the parent directory and then delete the parent directory.

For traversing the folder structure in Java there are two options-

  • File.listFiles()
  • Files.walkFileTree java 7 onward

Deleting directory recursively using File.listFiles() method

listFiles() method of the File class returns an array of abstract pathnames denoting the files in the directory denoted by this abstract pathname. You need to loop the array and recursively traverse files for the sub-directories to delete those files first and then the directories reaching up to the parent directory.

Directory structure used in the example.

Test
  \Temp
    \Child
      sub.txt
    \Empty Folder
    abc.txt
  bus.txt
  PDF in web.png
import java.io.File;
import java.io.IOException;

public class DeleteFileExp {
  public static void main(String[] args) throws IOException {
    // Source folder
    final String PARENT_DIR = "G:\\Test";
    File sourceDir = new File(PARENT_DIR);
    listFiles(sourceDir);
  }
 
  private static void listFiles(File parentDir){
    if(!parentDir.isDirectory()){
      System.out.println("Not a directory.");
      return;
    }
    File[] fileList = parentDir.listFiles();
    // iterate array 
    for(File file : fileList){
      // if it's a directory list files with in sub-directory for deletion
      if(file.isDirectory()){
        System.out.println("Directory- " + file.getName());
        listFiles(file);
      }else{                 
        System.out.println("Deleting File- " + file.getName());
        // if it is a file then delete it
        file.delete();
      }
    }
    // For deleting directories
    System.out.println("Deleting Directory - " + parentDir.getName());
    parentDir.delete();
  }
} 

Output

Deleting File- bus.txt
Deleting File- PDF in web.png
Directory- Temp
Deleting File- abc.txt
Directory- Child
Deleting File- sub.txt
Deleting Directory - Child
Directory- Empty Folder
Deleting Directory - Empty Folder
Deleting Directory - Temp
Deleting Directory – Test

Deleting directory recursively using Java Files.walkFileTree method

Using walkFileTree(Path start, FileVisitor<? super Path> visitor) method you can walk a file tree.

You need to implement FileVisitor interface, implementation of two of the methods of FileVisitor is required-

postVisitDirectory- To delete directory once it is empty
visitFile- to delete files when visited.

import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
public class DeleteFileExp {
  public static void main(String[] args) throws IOException {
    // Source folder
    final String PARENT_DIR = "G:\\Test";
    WalkStructure(PARENT_DIR);
  }
    
  private static void WalkStructure(String parentDir) throws IOException {
    Path sourcePath = Paths.get(parentDir);
    Files.walkFileTree(sourcePath, new SimpleFileVisitor<Path>(){
      @Override
      // After directory is visited and files deleted delete empty directory
      public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException {                    
        System.out.println("Deleting Directory- " + dir.toString());
        Files.delete(dir);
        return FileVisitResult.CONTINUE;
      }
      @Override
      // Delete each visited file
      public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException{
        System.out.println("Deleting file- " + file.getFileName());
        Files.delete(file);                
        return FileVisitResult.CONTINUE;
      }
    });  
  }
}

Output

Deleting file- bus.txt
Deleting file- PDF in web.png
Deleting file- abc.txt
Deleting file- sub.txt
Deleting Directory- G:\Test\Temp\Child
Deleting Directory- G:\Test\Temp\Empty Folder
Deleting Directory- G:\Test\Temp
Deleting Directory- G:\Test

That's all for this topic Java Program to Delete File And Directory Recursively. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. getPath(), getCanonicalPath() and getAbsolutePath() Methods in Java
  2. Read or List All Files in a Folder in Java
  3. How to Append to a File in Java
  4. How to Read Input From Console in Java
  5. Creating Tar File And GZipping Multiple Files in Java

You may also like-

  1. Creating PDF in Java Using Apache PDFBox
  2. DatabaseMetaData Interface in Java-JDBC
  3. Reflection in Java - Getting Class Information
  4. Difference Between Encapsulation And Abstraction in Java
  5. Java String Search Using indexOf(), lastIndexOf() And contains() Methods
  6. registerShutdownHook() Method in Spring Framework
  7. Spring Web MVC Tutorial
  8. Constructor in Python - __init__() function