Java Delete Directory deleteFiles(String directory, FileFilter filter, boolean recursive)

Here you can find the source of deleteFiles(String directory, FileFilter filter, boolean recursive)

Description

Removes all files in the given directory matching the given filter

License

Open Source License

Parameter

Parameter Description
directory the directory to be cleared
filter FileFilter used to filter files
recursive controls weather files should be deleted from sub directories too

Declaration

public static int deleteFiles(String directory, FileFilter filter, boolean recursive) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2010 Robert "Unlogic" Olofsson (unlogic@unlogic.se).
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser Public License v3
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl-3.0-standalone.html
 ******************************************************************************/

import java.io.File;
import java.io.FileFilter;

public class Main {
    /**//from w  w  w  .ja v  a  2  s .  c om
     * Removes all files in the given directory matching the given filter
     * 
     * @param directory
     *            the directory to be cleared
     * @param filter
     *            {@link FileFilter} used to filter files
     * @param recursive
     *            controls weather files should be deleted from sub directories too
     */
    public static int deleteFiles(String directory, FileFilter filter, boolean recursive) {

        return deleteFiles(new File(directory), filter, recursive);
    }

    public static int deleteFiles(File dir, FileFilter filter, boolean recursive) {

        if (dir.exists() && dir.isDirectory()) {

            int deletedFiles = 0;

            File[] files = dir.listFiles(filter);

            for (File file : files) {

                if (file.isDirectory()) {

                    if (recursive) {

                        deletedFiles += deleteFiles(file, filter, recursive);
                    }

                } else {

                    if (file.delete()) {

                        deletedFiles++;
                    }
                }
            }

            return deletedFiles;
        }

        return 0;
    }
}

Related

  1. deleteFiles(final File file)
  2. deleteFiles(final File... files)
  3. deleteFiles(List files)
  4. deleteFiles(String dir)
  5. deleteFiles(String dir, String... files)
  6. deleteFiles(String directoryName)
  7. deleteFiles(String fileName)
  8. deleteFiles(String root, String mask)
  9. deleteFiles(String sDir, String sSearch)