Java Delete Directory deleteDirectoryContents(File directory)

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

Description

delete Directory Contents

License

Apache License

Declaration

public static boolean deleteDirectoryContents(File directory) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;

public class Main {
    public static boolean deleteDirectoryContents(File directory) {
        Preconditions.checkArgument(directory.isDirectory(), "Not a directory: %s", directory);

        // Don't delete symbolic link directories
        if (isSymbolicLink(directory)) {
            return false;
        }/*  w w  w  .  j a v  a 2s .c o  m*/

        boolean success = true;
        for (File file : listFiles(directory)) {
            success = deleteRecursively(file) && success;
        }
        return success;
    }

    public static boolean isSymbolicLink(File file) {
        try {
            final File canonicalFile = file.getCanonicalFile();
            final File absoluteFile = file.getAbsoluteFile();
            final File parentFile = file.getParentFile();
            // a symbolic link has a different name between the canonical and absolute path
            return !canonicalFile.getName().equals(absoluteFile.getName()) ||
            // or the canonical parent path is not the same as the file's parent path,
            // provided the file has a parent path
                    parentFile != null && !parentFile.getCanonicalPath().equals(canonicalFile.getParent());
        } catch (IOException e) {
            // error on the side of caution
            return true;
        }
    }

    public static ImmutableList<File> listFiles(File dir) {
        File[] files = dir.listFiles();
        if (files == null) {
            return ImmutableList.of();
        }
        return ImmutableList.copyOf(files);
    }

    public static ImmutableList<File> listFiles(File dir, FilenameFilter filter) {
        File[] files = dir.listFiles(filter);
        if (files == null) {
            return ImmutableList.of();
        }
        return ImmutableList.copyOf(files);
    }

    public static boolean deleteRecursively(File file) {
        boolean success = true;
        if (file.isDirectory()) {
            success = deleteDirectoryContents(file);
        }

        return file.delete() && success;
    }
}

Related

  1. deleteDirectory(String dirname, boolean recursive)
  2. deleteDirectory(String fileName)
  3. deleteDirectory(String folder)
  4. deleteDirectory(String name)
  5. deleteDirectoryContent(final String strDir)
  6. deleteDirectoryContents(File directory)
  7. deleteDirectoryContents(File directory)
  8. deleteDirectoryContents(File directory)
  9. deleteDirectoryContents(File directory)