Java Delete Directory on Exit deleteDirectoryOnExit(final File dir)

Here you can find the source of deleteDirectoryOnExit(final File dir)

Description

Instructs Java to recursively delete the given directory (dir) and its contents when the JVM exits.

License

GNU General Public License

Parameter

Parameter Description
dir File customer representing directory to delete. If this file argument is not a directory, it will still be deleted. <p> The method works in Java 1.3, Java 1.4, Java 5.0 and Java 6.0; but it does not work with some early Java 6.0 versions See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6437591

Declaration

static void deleteDirectoryOnExit(final File dir) 

Method Source Code


//package com.java2s;

import java.io.File;

public class Main {
    /** Instructs Java to recursively delete the given directory (dir) and its contents when the JVM exits.
     *  @param dir File  customer  representing directory to delete. If this file argument is not a directory, it will still
     *  be deleted. <p>/*from  www.j a va2 s . c  o m*/
     *  The method works in Java 1.3, Java 1.4, Java 5.0 and Java 6.0; but it does not work with some early Java 6.0 versions
     *  See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6437591
     */
    static void deleteDirectoryOnExit(final File dir) {
        // Delete this on exit.  Delete on exit requests are processed in REVERSE order
        dir.deleteOnExit();

        // If it's a directory, visit its children.  This recursive walk has to be done AFTER calling deleteOnExit
        // on the directory itself because Java deletes the files to be deleted on exit in reverse order.
        if (dir.isDirectory()) {
            File[] childFiles = dir.listFiles();
            if (childFiles != null) { // listFiles may return null if there's an IO error
                for (File f : childFiles) {
                    deleteDirectoryOnExit(f);
                }
            }
        }
    }
}

Related

  1. deleteDirectoryOnExit(File directory)
  2. deleteDirectoryOnExit(File directory)
  3. deleteDirectoryOnExit(File directory)