How to delete a file in Java

1. Overview

It is very simple to delete file from specific directory. Java File class provides delete() method can be used to delete files or empty directory/folder in java. Java file delete method returns true if file gets deleted and returns false if file doesn’t exist.

2. Delete File Example

  1. Create a file named "sample.txt" in directory "C://workspace'.
  2. Create File class object by passing file absolute location path.
  3. call delete() method of file object to delete "sample.txt" file from 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 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");
  }
 }
}

3. Reference

Comments