Java Directory Clear cleanDirectory(File directory)

Here you can find the source of cleanDirectory(File directory)

Description

Deletes a directory (including any contents) and recreates it so that it is empty

License

Open Source License

Parameter

Parameter Description
directory a parameter

Declaration

public static void cleanDirectory(File directory) throws IOException 

Method Source Code

//package com.java2s;

import java.io.File;

import java.io.IOException;

public class Main {
    /**/*from  ww w  .  j  av a 2 s  .com*/
     * Deletes a directory (including any contents) and recreates it so that it
     * is empty
     * 
     * @param directory
     * @return
     */
    public static void cleanDirectory(File directory) throws IOException {
        deleteDirectory(directory);
        if (!directory.mkdirs())
            throw new IOException("Directory could not be re-created during clean: " + directory.getAbsolutePath());
    }

    /**
     * Recursively deletes the contents of a directory, and the directory itself
     * 
     * @param directory
     * @return
     */
    public static boolean deleteDirectory(File directory) {
        boolean success = true;

        if (directory.exists()) {

            // delete contents
            File[] files = directory.listFiles();
            for (File f : files) {
                if (f.isDirectory()) {
                    success = success && deleteDirectory(f);
                } else {
                    success = success && f.delete();
                }
            }

            // delete directory itself
            success = success && directory.delete();
        }

        return success;
    }
}

Related

  1. cleanDirectory(File dir)
  2. cleanDirectory(File dir)
  3. cleanDirectory(File dir)
  4. cleanDirectory(File dir, boolean deleteDirectory)
  5. cleanDirectory(File directory)
  6. cleanDirectory(File directory)
  7. cleanDirectory(File directory)
  8. cleanDirectory(File directory)
  9. cleanDirectory(File directory)