Java Delete File or Directory deleteFileOrDirOnExit(File filehandle)

Here you can find the source of deleteFileOrDirOnExit(File filehandle)

Description

Delete file or folder recursively on exit of the program

License

Open Source License

Parameter

Parameter Description
filehandle a parameter

Return

true if all went well

Declaration

public static boolean deleteFileOrDirOnExit(File filehandle) 

Method Source Code

//package com.java2s;
/*// w  w w . j a  v  a2s . c om
 * Stage - Spatial Toolbox And Geoscript Environment 
 * (C) HydroloGIS - www.hydrologis.com 
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * (http://www.eclipse.org/legal/epl-v10.html).
 */

import java.io.File;

public class Main {
    /**
     * Delete file or folder recursively on exit of the program
     * 
     * @param filehandle
     * @return true if all went well
     */
    public static boolean deleteFileOrDirOnExit(File filehandle) {
        if (filehandle.isDirectory()) {
            String[] children = filehandle.list();
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteFileOrDir(new File(filehandle, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        filehandle.deleteOnExit();
        return true;
    }

    /**
     * Returns true if all deletions were successful. If a deletion fails, the method stops
     * attempting to delete and returns false.
     * 
     * @param filehandle
     * @return true if all deletions were successful
     */
    public static boolean deleteFileOrDir(File filehandle) {

        if (filehandle.isDirectory()) {
            String[] children = filehandle.list();
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteFileOrDir(new File(filehandle, children[i]));
                if (!success) {
                    return false;
                }
            }
        }

        // The directory is now empty so delete it
        boolean isdel = filehandle.delete();
        if (!isdel) {
            // if it didn't work, which often happens on windows systems,
            // remove on exit
            filehandle.deleteOnExit();
        }

        return isdel;
    }
}

Related

  1. deleteFileOrDirectory(File dir)
  2. deleteFileOrDirectory(File file)
  3. deleteFileOrDirectory(File fileOrDirectory)
  4. deleteFileOrDirectory(String fileName)
  5. deleteFileOrDirectoryRecursive(String dir)
  6. deleteFileOrFolder(File fileOrFolder)