Java Delete Directory on Exit deleteDirectoryOnExit(File directory)

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

Description

delete Directory On Exit

License

Open Source License

Parameter

Parameter Description
directory directory to delete.

Exception

Parameter Description
IOException in case deletion is unsuccessful

Declaration

private static void deleteDirectoryOnExit(File directory) throws IOException 

Method Source Code


//package com.java2s;
import java.io.*;

public class Main {
    /**/*from ww w . j  ava2s .co  m*/
     *
     * @param directory directory to delete.
     * @throws IOException in case deletion is unsuccessful
     */
    private static void deleteDirectoryOnExit(File directory) throws IOException {
        if (!directory.exists()) {
            return;
        }

        cleanDirectoryOnExit(directory);
        directory.deleteOnExit();
    }

    /**
     *
     * @param directory directory to clean.
     * @throws IOException in case cleaning is unsuccessful
     */
    private static void cleanDirectoryOnExit(File directory) throws IOException {
        if (!directory.exists()) {
            String message = directory + " does not exist";
            throw new IllegalArgumentException(message);
        }

        if (!directory.isDirectory()) {
            String message = directory + " is not a directory";
            throw new IllegalArgumentException(message);
        }

        IOException exception = null;

        File[] files = directory.listFiles();
        for (int i = 0; i < files.length; i++) {
            File file = files[i];
            try {
                forceDeleteOnExit(file);
            } catch (IOException ioe) {
                exception = ioe;
            }
        }

        if (null != exception) {
            throw exception;
        }
    }

    /**
     * force delete file or directory
     *
     * @param file file or directory to delete.
     * @throws IOException in case deletion is unsuccessful
     */
    public static void forceDeleteOnExit(File file) throws IOException {
        if (file.isDirectory()) {
            deleteDirectoryOnExit(file);
        } else {
            file.deleteOnExit();
        }
    }
}

Related

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