Sep 23

Use the listFiles() method of the File class to iterate through all the files in a directory. The isDirectory() method can be used to determine which are directories.


public static void traverse(File directory)
{
   // Get all files in directory

   File[] files = directory.listFiles();
   for (File file : files)
   {
      if (file.isDirectory())
      {
         // Its a directory so (recursively) traverse it

         traverse(file);
      }
      else
      {
         // its a file, do any processing you require here
      }
   }
}

written by objects \\ tags: , ,

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: , ,