Java Force Delete on Exit forceDeleteOnExit(File file)

Here you can find the source of forceDeleteOnExit(File file)

Description

force delete file or directory

License

Open Source License

Parameter

Parameter Description
file file or directory to delete.

Exception

Parameter Description
IOException in case deletion is unsuccessful

Declaration

public static void forceDeleteOnExit(File file) throws IOException 

Method Source Code


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

public class Main {
    /**/*from  ww w.j a  v a2s. c o  m*/
     * 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();
    }

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

Related

  1. forceDeleteOnExit(File file)
  2. forceDeleteOnExit(File file)