Program to demonstrate how to delete a file/directory and its contents using a simple Java program.
Output of the program :
package com.hubberspot.example; import java.io.File; 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("java.io.tmpdir") // We can delete files of any specified location of our machine. String tempFileName = System.getProperty("java.io.tmpdir"); System.out.println(tempFileName); // 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 file.delete(); // 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 :