How to delete a file or directory in Java using NIO API

Tutorial shows how to delete a file or directory in Java using NIO API’s java.nio.file.Files class’s delete() and deleteIfExists() methods. For each of the methods, we will go through the method definition, exception scenarios, and then see via code examples how to use Files.delete() and Files.deleteIfExists() methods to delete files or directories in Java.

Important Note – Java considers both files and directories as ‘files’ similar to Unix philosophy of ‘everything is a file’. For example, deleteFile() method works for both files and directories. Henceforth in this tutorial a file can mean either a file and/or a directory unless explicitly specified.

Deleting files using Files.delete() method
Files.delete() method is defined with the following signature –

public static void delete(Path path) throws IOException

Where,
     – only input parameter is path which is an instance of java.nio.file.Path.

Files.delete() method deletes the file specified using the Path instance. Since, the delete() method doesn’t return anything when it is successful, hence, the method is said to have successfully deleted the file passed to it when no instance of an IOException(or its sub-types) is thrown.

For UNIX-based file systems, if the Path instance being deleted contains a symbolic link to a file, then Files.delete() method will only delete the symbolic link, and not the file that it points to.

Files.delete() method throws IOException or its sub-types in the following cases –

  1. NoSuchFileException is thrown when the file being deleted does not exist.
  2. DirectoryNotEmptyException is thrown when the directory being deleted is not empty.
  3. IOException is thrown when an IO(Input/Output) error occurs.

Let us now see a code example showing Files.delete() method in action, including couple of commonly occurring exception scenarios. The directory structure which will be used for file deletion is simple – a directory named Level1 with path C:\JavaBrahman\Level1, and this directory has a single file named file1.txt.

Level1       (dir)
|- – – file1.txt     (file)
Java code example showing Files.delete() method usage
package com.javabrahman.corejava;

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

public class FileDirDelete {

  public static void main(String args[]) {

      //STEP 1: Level1 dir exists but is not empty
      System.out.println("STEP-1");
      Path dirPath_1 = Paths.get("C:\\JavaBrahman\\Level1");
      try {
        Files.delete(dirPath_1);
      } catch (IOException ioException) {
        System.out.println("Error caught in deleting directory");
        ioException.printStackTrace();
      }

      //STEP 2: file1.txt file exists
      System.out.println("STEP-2");
      Path filePath_1 = Paths.get("C:\\JavaBrahman\\LEVEL1\\file1.txt");
      System.out.println("file1.txt exists before delete:" + Files.exists(filePath_1));
      try {
        Files.delete(filePath_1);
      } catch (IOException ioException) {
        System.out.println("Error caught");
        ioException.printStackTrace();
      }
      System.out.println("file1.txt exists after delete:" + Files.exists(filePath_1));

      //STEP 3: Level1 dir exists and is empty
      System.out.println("STEP-3");
      System.out.println("Level1 directory exists before delete:" + Files.exists(dirPath_1));
      try {
        Files.delete(dirPath_1);
      } catch (IOException ioException) {
        System.out.println("Error caught in deleting directory");
        ioException.printStackTrace();
      }
      System.out.println("Level1 directory exists after delete:" + Files.exists(dirPath_1));

      //STEP 4: file1.txt doesn't exist
      System.out.println("STEP-4");
       try {
        Files.delete(filePath_1);
      } catch (IOException ioException) {
        System.out.println("Error caught in deleting file");
        ioException.printStackTrace();
      }
  }
}
 OUTPUT of the above code
STEP-1
Error caught in deleting directory
java.nio.file.DirectoryNotEmptyException: C:\JavaBrahman\Level1
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.javabrahman.corejava.FileDirDelete.main(FileDirDelete.java:17)

STEP-2
file1.txt exists before delete: true
file1.txt exists after delete: false

STEP-3
Level1 directory exists before delete: true
Level1 directory exists after delete: false

STEP-4
Error caught in deleting file
java.nio.file.NoSuchFileException: C:\JavaBrahman\LEVEL1\file1.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.javabrahman.corejava.FileDirDelete.main(FileDirDelete.java:53)

Explanation of the code

  • The above code shows 4 scenarios for file deletion marked as 4 steps in the code.
  • STEP 1: Level1 directory is deleted using Files.delete() method. Since, Level1 is not empty, as it contains file1.txt, DirectoryNotEmptyException is thrown.
  • STEP 2: file1.txt inside Level1 directory is deleted using Files.delete() method. Files.exists() method is used to check for existence of file1.txt before and after executing the delete method. As indicated by the output, file1.txt is indeed deleted.
  • STEP 3: Level1 directory is now empty. Calling of Files.delete() method for Level1 directory now deletes the directory. Checking with Files.exists() shows that Level1 has been deleted successfully.
  • STEP 4: An attempt to delete the already deleted file1.txt throws a NoSuchFileException.

Deleting files using Files.deleteIfExists() method
Files.deleteIfExists() method is defined with the following signature –

public static boolean deleteIfExists(Path path) throws IOException

Where,
     – only input parameter is path which is an instance of java.nio.file.Path
     – output is a boolean value indicating file was successfully deleted(true) or wasn’t deleted(false).

Files.deleteIfExists() method deletes the file specified using the Path instance. It returns a boolean value indicating whether the file was deleted or not.

Similar to Files.delete() method, for UNIX-based file systems, if the Path instance being deleted contains a symbolic link to a file, then Files.deleteIfExists() method will only delete the symbolic link, and not the file that it points to.

Files.deleteIfExists() method throws IOException or its sub-types in the following cases –

  1. DirectoryNotEmptyException is thrown when the directory being deleted is not empty.
  2. IOException is thrown when an IO(Input/Output) error occurs.

Let us now see a code example showing Files.deleteIfExists() method in action. The directory structure which will be used for file deletion is same as Files.delete() example we saw earlier – a directory Level1 with path C:\JavaBrahman\Level1, which has a single file file1.txt.

Java code example showing Files.deleteIfExists() method usage
package com.javabrahman.corejava;

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

public class FileDirDelete {

  public static void main(String args[]) {

      //STEP 1: Level1 dir exists but is not empty
      System.out.println("STEP-1");
      Path dirPath_1 = Paths.get("C:\\JavaBrahman\\Level1");
      try {
        Files.deleteIfExists(dirPath_1);
      } catch (IOException ioException) {
        System.out.println("Error caught in deleting directory");
        ioException.printStackTrace();
      }

      //STEP 2: file1.txt file exists
      System.out.println("STEP-2");
      Path filePath_1 = Paths.get("C:\\JavaBrahman\\LEVEL1\\file1.txt");
      boolean isFileDeleted = false;
      try {
        isFileDeleted = Files.deleteIfExists(filePath_1);
      } catch (IOException ioException) {
        System.out.println("Error caught");
        ioException.printStackTrace();
      }
      System.out.println("file1.txt has been deleted:" + isFileDeleted);

      //STEP 3: Level1 dir exists and is empty
      System.out.println("STEP-3");
      boolean isDirDeleted = false;
      try {
        isDirDeleted = Files.deleteIfExists(dirPath_1);
      } catch (IOException ioException) {
        System.out.println("Error caught in deleting directory");
        ioException.printStackTrace();
      }
      System.out.println("Level1 directory has been deleted:" + isDirDeleted);
  }

}
 OUTPUT of the above code
STEP-1
Error caught in deleting directory
java.nio.file.DirectoryNotEmptyException: C:\JavaBrahman\Level1
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.javabrahman.corejava.FileDirDelete.main(FileDirDelete.java:17)

STEP-2
file1.txt has been deleted: true

STEP-3
Level1 directory has been deleted: true

Explanation of the code

  • The above code shows 3 scenarios for file deletion marked as3 steps in the code.
  • STEP 1: Level1 directory is deleted using Files.deleteIfExists() method. Since, Level1 is not empty, as it contains file1.txt, DirectoryNotEmptyException is thrown.
  • STEP 2: file1.txt inside Level1 directory is deleted using Files.deleteIfExists() method. The boolean value returned by the deleteIfExists() method is stored in a variable named isFileDeleted, the value of which is printed after deletion to confirm that file1.txt is indeed deleted.
  • STEP 3: Level1 directory is now empty. The boolean value returned by the deleteIfExists() method is stored in a variable named isDirDeleted, the value of which is printed after deletion to confirm that Level1 directory is successfully deleted.

Files.delete() versus Files.deleteIfExists()
There are 2 differences between Files.delete() and Files.deleteIfExists() method and both seem to tilt the balance in favor of deleteIfExists() method.

The first difference is that deleteIfExists() returns a boolean method indicating the method’s success while the delete() method doesn’t return anything. It is much easier to write and understand code which uses a true/false value to determine how to proceed(deleteIfExists()) when compared to coding for a condition where the absence of an exception implies sucessfull file delete(delete()).

The second difference is the handling of ‘file does not exist scenario’. While delete() method throws a NoSuchFileException when there is no file at the provided Path, deleteIfExists() simply returns a false value. While this may seem hard to determine the cause when using deleteIfExists() in case the file is not deleted, but in case of multi-threaded applications a silent ‘consumption’ of file-not-found error works better than an exception which derails the system by raising an alarm, as will happen for delete() method throwing NoSuchFileException. So, unless you really need to code for a scenario where the user needs to informed the cause of file not getting deleted, deleteIfExists() is better suited for file-not-found scenario as well.

What if you need to delete an entire directory structure recursively
The above code examples show how to delete an individual file/empty directory. In case you need to recursively delete a directory and all the directories/files it contains similar to the way a "DELTREE" command works in DOS or "rm -rf" in UNIX, then you will need to recursively visitClick to Read Tutorial showing how to recursively walk a file tree using SimpleFileVisitor the entire directory structure below the given directory using SimpleFileVisitor, and delete all the files and directories in it individually.

 

Digiprove sealCopyright © 2014-2017 JavaBrahman.com, all rights reserved.