Delete File in Java

In this quick tutorial, we will learn how to delete a file in Java. 

We will see two ways to delete a file in Java:
  1. Delete the file using the delete() method of the class
  2. Delete the file using Files.delete(Path) method of Java NIO

1. Delete the File using File.delete() Method

  1. Create a file named "sample.txt" in the directory "C://workspace'.
  2. Create a File class object and pass the file's absolute location path.
  3. call the delete() method of the file object to delete the "sample.txt" file from the directory "C://workspace"
  4. delete() method returns true if and only if the file or directory is successfully deleted; false otherwise.
  5. Observe the directory whether the file is deleted or not.

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

 * This Java program demonstrates how to delete a file in Java.
 * @author

public class DeleteFileExample {
    private static final Logger LOGGER = LoggerFactory

    public static void main(String[] args) {
    public static void deleteFile() {
        File file = new File("C://workspace/sample.txt");
        if (file.delete()) {
   + "created !!");
        } else {
  "Delete operation failed");

2. Delete File using Java NIO’s Files.delete() 

It is recommended to use Java NIO’s Files.delete() method to delete the file in Java:
import java.nio.file.*;

public class DeleteFileExample {
    public static void main(String[] args) throws IOException {
        // File or Directory to be deleted
        Path path = Paths.get("./demo.txt");

        try {
            // Delete file or directory
            System.out.println("File or directory deleted successfully");
        } catch (NoSuchFileException ex) {
            System.out.printf("No such file or directory: %s\n", path);
        } catch (DirectoryNotEmptyException ex) {
            System.out.printf("Directory %s is not empty\n", path);
        } catch (IOException ex) {