Java Directory Clean clearDir(String dirPath)

Here you can find the source of clearDir(String dirPath)

Description

Deletes all files in the specified directory, recursively.

License

Apache License

Parameter

Parameter Description
dirPath Path of the directory to clear. The directory itself is not deleted.

Declaration

public static void clearDir(String dirPath) 

Method Source Code


//package com.java2s;
/*/*w  w w  .jav a2s .c  o m*/
 * Copyright 2015 Jeff Hain
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.io.File;

public class Main {
    private static final boolean DEBUG = false;

    /**
     * Deletes all files in the specified directory, recursively.
     * 
     * @param dirPath Path of the directory to clear. The directory itself
     *        is not deleted.
     */
    public static void clearDir(String dirPath) {
        if (DEBUG) {
            System.out.println("clearDir(" + dirPath + ")");
        }
        final File dir = new File(dirPath);
        final String[] childList = dir.list();
        if (childList == null) {
            return;
        }
        for (String childName : childList) {
            final File child = new File(dirPath + "/" + childName);
            if (child.isDirectory()) {
                clearDir(child.getAbsolutePath());
            }
            final boolean didIt = child.delete();
            if (!didIt) {
                throw new RuntimeException("could not delete " + child.getAbsolutePath());
            }
        }
    }
}

Related

  1. cleanDirectory(File currentDir)
  2. cleanPath(String loc)
  3. cleanPath(String path)
  4. cleanPaths(String root, String rel, String name)
  5. clearDir(File dir, boolean clearsubdirs)