Java Delete Directory deleteDirectoryContents(File directory)

Here you can find the source of deleteDirectoryContents(File directory)

Description

Wipes out all the a directory starting from a given directory.

License

Apache License

Parameter

Parameter Description
directory to be cleaned

Exception

Parameter Description

Declaration

public static void deleteDirectoryContents(File directory) throws IOException 

Method Source Code


//package com.java2s;
/*//w  ww .ja va  2s  .  c  o  m
 * Copyright ? 2014 Cask Data, Inc.
 *
 * 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 com.google.common.base.Preconditions;
import com.google.common.collect.Queues;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.Deque;

public class Main {
    /**
     * Wipes out all the a directory starting from a given directory.
     * @param directory to be cleaned
     * @throws java.io.IOException
     */
    public static void deleteDirectoryContents(File directory) throws IOException {
        Preconditions.checkArgument(directory.isDirectory(), "Not a directory: %s", directory);
        Deque<File> stack = Queues.newArrayDeque();
        stack.add(directory);

        while (!stack.isEmpty()) {
            File file = stack.peekLast();
            File[] files = file.listFiles();
            if (files == null || files.length == 0) {
                file.delete();
                stack.pollLast();
            } else {
                Collections.addAll(stack, files);
            }
        }
    }
}

Related

  1. deleteDirectory(String name)
  2. deleteDirectoryContent(final String strDir)
  3. deleteDirectoryContents(File directory)
  4. deleteDirectoryContents(File directory)
  5. deleteDirectoryContents(File directory)
  6. deleteDirectoryContents(File directory)
  7. deleteDirectoryContents(final File dir)
  8. deleteDirectoryContents(final File dir, int deleteDirLevel, int level)
  9. deleteFiles(File dir)