July 9, 2021

Delete a File or Directory Using a Java Program

This post shows how to delete a file or directory using a Java program and how to delete a directory recursively in Java. For deleting a file or directory, Java provides following options.

  • delete()- You can use the delete method of java.io.File class. This method deletes the file or directory denoted by this abstract pathname. If you are trying to delete a directory, then the directory must be empty in order to be deleted. Method returns true if the file or directory is successfully deleted otherwise returns false.
  • Files.delete(Path path)- Java 7 onward Files.delete() method can be used to delete a file or directory. For deleting a directory it must be ensured that the directory is empty. This method throws NoSuchFileException if the file does not exist and throws DirectoryNotEmptyException if the file is a directory and could not otherwise be deleted because the directory is not empty.
  • Files.deleteIfExists(Path path)- Another option in Files class to delete a file or directory is to use deleteIfExists() method. This method deletes a file or folder if it exists and returns true if the file was deleted by this method; false if the file could not be deleted because it did not exist. Same restriction for the directory applies that directory must be empty.

In the post we’ll see Java examples of deleting files and directories using the above mentioned methods. We’ll also see how to delete a non-empty directory by recursively deleting the files and sub-directories and ultimately deleting the parent directory.

Deleting file using java.io.File delete method

In the example code all the scenarios are covered-

  1. A file that exists at the given path is deleted.
  2. Trying to delete a file that doesn’t exist.
  3. Deleting an empty directory.
  4. Trying to delete non-empty directory.
public class DeleteFile {
  public static void main(String[] args) {
    File file = new File("F:\\knpcode\\Test\\postend.txt");
    fileDelete(file);

    // trying to delete file that doesn't exist
    file = new File("F:\\knpcode\\Test\\postend.txt");
    fileDelete(file);

    // Deleting empty directory
    file = new File("F:\\knpcode\\Test");
    fileDelete(file);

    // Deleting non-empty directory
    file = new File("F:\\knpcode\\Parent");
    fileDelete(file);
  }
	
  private static void fileDelete(File file){
    if(file.delete()){
      System.out.println("File " + file.getName() + " deleted successfully");
    }else{
      System.out.println("File " + file.getName() + " not deleted as it doesn't exist/non-empty directory");
    }
  }
}
Output
File postend.txt deleted successfully
File postend.txt not deleted as it doesn't exist/non-empty directory
File Test deleted successfully
File Parent not deleted as it doesn't exist/non-empty directory

Deleting file using Files delete and deleteIfExists method

Files.delete method to delete file

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

public class DeleteFile {
  public static void main(String[] args) {
    try {
      Files.delete(Paths.get("F:\\knpcode\\Test\\postend.txt"));
      // deleting same file again - file that doesn't exist scenario
      Files.delete(Paths.get("F:\\knpcode\\Test\\postend.txt"));
    } catch (NoSuchFileException e) {	
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    catch (DirectoryNotEmptyException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}
Output
java.nio.file.NoSuchFileException: F:\knpcode\Test\postend.txt
	at sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:79)
	at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:97)
	at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:102)
	at sun.nio.fs.WindowsFileSystemProvider.implDelete(WindowsFileSystemProvider.java:269)
	at sun.nio.fs.AbstractFileSystemProvider.delete(AbstractFileSystemProvider.java:103)
	at java.nio.file.Files.delete(Files.java:1126)
	at com.knpcode.programs.DeleteFile.main(DeleteFile.java:16)

Files.deleteIfExists method to delete file

public class DeleteFile {

  public static void main(String[] args) {
    try {
      if(Files.deleteIfExists(Paths.get("F:\\knpcode\\Test\\postend.txt")))
        System.out.println("File deleted successfully");
      else
        System.out.println("File not deleted");
      // deleting same file again - file that doesn't exist scenario
      if(Files.deleteIfExists(Paths.get("F:\\knpcode\\Test\\postend.txt")))
        System.out.println("File deleted successfully");
      else
        System.out.println("File not deleted");
    }
    catch (DirectoryNotEmptyException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}
Output
File deleted successfully
File not deleted

Files.delete method to delete folder in Java

public class DeleteFile {
  public static void main(String[] args) {
    try {      
      // Deleting empty directory
      Files.delete(Paths.get("F:\\knpcode\\Test"));
      
      // Deleting non-empty directory
      Files.delete(Paths.get("F:\\knpcode\\Parent"));
      
    } catch (NoSuchFileException e) {	
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    catch (DirectoryNotEmptyException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}
Output
java.nio.file.DirectoryNotEmptyException: F:\knpcode\Parent
	at sun.nio.fs.WindowsFileSystemProvider.implDelete(WindowsFileSystemProvider.java:266)
	at sun.nio.fs.AbstractFileSystemProvider.delete(AbstractFileSystemProvider.java:103)
	at java.nio.file.Files.delete(Files.java:1126)
	at com.knpcode.programs.DeleteFile.main(DeleteFile.java:22)

Deleting non-empty directory recursively in Java

As you can see from the above examples directory should be empty to be deleted, in case of non-empty directory it is not deleted. For deleting a non-empty directory you need to recursively walk through the folder structure and delete all the files and sub-directories before deleting the parent directory which is empty by then.

For recursively deleting a file in Java there are two options-

  1. Using File.listFiles() method which returns an array of abstract pathnames denoting the files in the directory. Then you can iterate the array to delete the files and you will have to recursively call your method to delete files with in the sub-directories.
  2. Java 7 onward you can use Files.walkFileTree() method which walks a file tree rooted at a given starting file.

Directory structure used

Java programs shown here to delete a non-empty directory in Java use the following directory structure.

delete directory using Java

With in the parent folder there are two sub-folders Child with two files and Empty with no file. One file is stored in the parent folder.

Deleting directory recursively using File.listFiles() method

public class DeleteDirectory {
  public static void main(String[] args) {
    // Source folder
    final String SOURCE_DIR = "F:/knpcode/Parent";
    File sourceDir = new File(SOURCE_DIR);
    directoryDeletion(sourceDir);
  }
	
  private static void directoryDeletion(File sourceDir){
    if(!sourceDir.isDirectory()){
      System.out.println("Not a directory.");
      return;
    }
    File[] fileList = sourceDir.listFiles();
    for(File file : fileList){
      // if directory call method recursively to 
      // list files with in sub-directories for deletion
      if(file.isDirectory()){
        System.out.println("Sub Directory- " + file.getName());
        directoryDeletion(file);
      }else{				 
        System.out.println("Deleting file- " + file.getName());
        // if it is a file then delete it
        file.delete();
      }
    }
    // For deleting sub-directories and parent directory
    System.out.println("Deleting Directory - " + sourceDir.getName());
    sourceDir.delete();
  }
}
Output
Sub Directory- Child
Deleting file- hello.txt
Deleting file- Project.docx
Deleting Directory - Child
Sub Directory- Empty
Deleting Directory - Empty
Deleting file- Test.txt
Deleting Directory – Parent

Deleting directory recursively using Java Files.walkFileTree method

Java 7 onward You can use Files.walkFileTree() method using which you can walk the tree structure of the source directory and delete all the files and sub-directories in the process. One of the argument of this method is a FileVisitor interface. You do need to provide implementation of this interface as per your requirement.

FileVisitor interface has four methods, for deleting directory recursively you do need to implement two of them; postVisitDirectory() (to delete directory after visiting all the files) and visitFile (to delete files).

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 DeleteDirectory {
  public static void main(String[] args) {
    // Source folder
    final String SOURCE_PATH = "F:/knpcode/Parent";
    try {
      directoryDeletion(SOURCE_PATH);
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
  }
	
  private static void directoryDeletion(String sourceDir) throws IOException {
    Path sourcePath = Paths.get(sourceDir);
    Files.walkFileTree(sourcePath, new SimpleFileVisitor<Path>(){
      @Override
      // Before visiting the directory, create directory 
      public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException {		    		
        System.out.println("Deleting Directory- " + dir.toString());
        Files.delete(dir);
        return FileVisitResult.CONTINUE;
      }
      @Override
      // For each visited file delete it
      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- hello.txt
Deleting file- Project.docx
Deleting Directory- F:\knpcode\Parent\Child
Deleting Directory- F:\knpcode\Parent\Empty
Deleting file- Test.txt
Deleting Directory- F:\knpcode\Parent

That's all for the topic Delete a File or Directory Using a Java Program. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment