Free Data Structures and Algorithms Course

Subscribe below and get all best seller courses for free !!!


Subscribe to all free courses

How to delete a file/directory and its contents using a simple Java program

Program to demonstrate how to delete a file/directory and its contents using a simple Java program.

package com.hubberspot.example;


public class DirectoryFilesDelete {

 public static void main(String[] args) {
  // 1. Get the directory name for which you have to perform 
  // deletions. I am using here our machine's temp folder 
  // which we can get by calling System.getProperty("")
  // We can delete files of any specified location of our machine.
  String tempFileName = System.getProperty("");


  // 2. Create a File object which will point to this temp 
  // directory.
  File directory = new File(tempFileName);

  // 3. Get all files in directory using the method listFiles()
  File[] files = directory.listFiles();

  // 4. Loop through each file and call delete() on it

  for (File file : files)
   // 5. This will loop each file/directory and delete file

   // 6. If it cannot delete the file it prints the name 
   // of file it cant delete
   if (!file.delete())
    System.out.println("Failed to delete : "+ file);



Output of the program :

© 2021 Learn Java by Examples Template by Hubberspot