Java Delete Tree deleteTree(File dir)

Here you can find the source of deleteTree(File dir)

Description

Recursively delete a directory and all of its contents.

License

Open Source License

Parameter

Parameter Description
dir The directory to delete

Declaration

public static boolean deleteTree(File dir) 

Method Source Code

//package com.java2s;
/* ************************************************************************
 *
 *  TMPotter - Bi-text Aligner/TMX Editor.
 *
 *  Copyright (C) 2005-2009 Raymond: Martin
 *            (C) 2015 Hiroshi Miura//from  w  w w. j  a  v  a  2  s .  com
 *
 *  Copyright (C) 2008 Alex Buloichik
 *                2009 Didier Briel,  2012 Alex Buloichik, Didier Briel
 *                2014 Alex Buloichik, Aaron Madlon-Kay
 *
 *  This file is part of TMPotter.
 *
 *  TMPotter is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  TMPotter is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 * 
 *  You should have received a copy of the GNU General Public License
 *  along with TMPotter.  If not, see http://www.gnu.org/licenses/.
 *
 * *************************************************************************/

import java.io.File;

public class Main {
    /**
     * Recursively delete a directory and all of its contents.
     *
     * @param dir The directory to delete
     */
    public static boolean deleteTree(File dir) {
        if (!dir.exists()) {
            return false;
        }
        if (dir.isDirectory()) {
            File[] files = dir.listFiles();
            if (files == null) {
                return false;
            }
            for (File file : files) {
                if (file.isDirectory()) {
                    // recursive delete
                    if (!deleteTree(file)) {
                        return false;
                    }
                    continue;
                }
                // recursive leaf/file
                if (file.isFile()) {
                    if (!file.delete()) {
                        return false;
                    }
                    continue;
                }
                // other condition?
                // TODO
            }
        }
        return dir.delete();
    }
}

Related

  1. deleteTree(File dir)
  2. deleteTree(File f)
  3. deleteTree(File file, boolean check)
  4. deleteTree(final File file)