Java Delete Directory deleteFilesInDir(File dir)

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

Description

Recursively deletes all the files of the specified directory.

License

Open Source License

Parameter

Parameter Description
dir a parameter

Declaration

public static void deleteFilesInDir(File dir) 

Method Source Code

//package com.java2s;
/*//from w  w w  .  j  av a2 s . com
 * (c) Copyright 2010-2011 AgileBirds
 *
 * This file is part of OpenFlexo.
 *
 * OpenFlexo 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.
 *
 * OpenFlexo 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 OpenFlexo. If not, see <http://www.gnu.org/licenses/>.
 *
 */

import java.io.File;

public class Main {
    /**
     * Recursively deletes all the files of the specified directory. Directories themselves are not removed.
     * 
     * @param dir
     */
    public static void deleteFilesInDir(File dir) {
        deleteFilesInDir(dir, false);
    }

    public static void deleteFilesInDir(File dir, boolean keepCVSTags) {
        if (!dir.isDirectory()) {
            System.err.println("Tried to delete a directory but file is not a directory: " + dir.getAbsolutePath());
            return;
        }
        if (keepCVSTags && dir.getName().equals("CVS")) {
            System.err.println("Tried to delete CVS directory but keepCVSTags flag is true!");
            return;
        }

        File[] f = dir.listFiles();
        if (f == null) {
            return;
        }
        for (int i = 0; i < f.length; i++) {
            File file = f[i];
            if (file.isDirectory()) {
                if (!file.getName().equals("CVS") || !keepCVSTags) {
                    deleteFilesInDir(file, keepCVSTags);
                }
            } else {
                file.delete();
            }
        }
    }
}

Related

  1. deleteFiles(String[] filenames)
  2. deleteFilesAndDir(List files)
  3. deleteFilesAndSubDirs(File dir)
  4. deleteFilesFromDirectory(final String dirNameIn, final String filePrefixIn)
  5. deleteFilesInDir(File dir)