Java Directory Delete on Exit cleanDirectoryOnExit(File directory)

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

Description

clean Directory On Exit

License

Open Source License

Parameter

Parameter Description
directory directory to clean.

Exception

Parameter Description
IOException in case cleaning is unsuccessful

Declaration

private static void cleanDirectoryOnExit(File directory) throws IOException 

Method Source Code


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

public class Main {
    /**//from  w  w w .ja va2 s. co  m
     *
     * @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();
        }
    }

    /**
     *
     * @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();
    }
}

Related

  1. cleanDirectoryOnExit(File directory)