Sep 23

Use the listFiles() method of the File class to iterate through all the files in the directory. The File classes delete() method is then used to delete each file.

Remember to check the return value from the call to verify it was deleted successfully.

File directory = new File(directoryName);

// Get all files in directory

File[] files = directory.listFiles();
for (File file : files)
{
   // Delete each file

   if (!file.delete())
   {
       // Failed to delete file

       System.out.println("Failed to delete "+file);
   }
} 

written by objects \\ tags: , ,


2 Responses to “How to delete all files in a directory?”

  1. joseph Says:

    Just what I needed in our Exam in java…HAHA!!!

  2. Khaled Says:

    Great ^_^

Leave a Reply

You must be logged in to post a comment.