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 java.io.File 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 java.io.File;

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

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

public class DeleteFileExample {
    private static final Logger LOGGER = LoggerFactory
        .getLogger(DeleteFileExample.class);

    public static void main(String[] args) {
        deleteFile();
    }
    public static void deleteFile() {
        File file = new File("C://workspace/sample.txt");
        if (file.delete()) {
            LOGGER.info(file.getName() + "created !!");
        } else {
            LOGGER.info("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.io.IOException;
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
            Files.delete(path);
            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) {
            System.out.println(ex);
        }
    }
}

Reference

Comments