Java Folder Delete clearFolder(String path)

Here you can find the source of clearFolder(String path)

Description

Delete all files in the directory except folders.

License

Apache License

Parameter

Parameter Description
path - directory path

Return

- true if successfully, otherwise false.

Declaration

public static boolean clearFolder(String path) 

Method Source Code

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

import java.io.File;

public class Main {
    /**//from   www. ja v  a 2 s.c  om
     * Delete all files in the directory except folders. Directory may end with
     * a "\" or not.
     * 
     * @param path
     *            - directory path
     * @return - true if successfully, otherwise false.
     */
    public static boolean clearFolder(String path) {
        boolean flag = true;
        File dirFile = new File(path);
        if (!dirFile.isDirectory()) {
            return flag;
        }
        File[] files = dirFile.listFiles();
        for (File file : files) {
            // Delete files.
            if (file.isFile()) {
                flag = deleteFile(file);
                if (!flag) {
                    break;
                }
            }
        }
        return flag;
    }

    /**
     * Delete file according to a path.
     * 
     * @param path
     *            - file path
     * @return - true if delete successfully, otherwise false.
     */
    public static boolean deleteFile(String path) {
        File file = new File(path);
        return deleteFile(file);
    }

    /**
     * Delete file.
     * 
     * @param file
     *            - deleted file
     * @return - true if delete successfully, otherwise false.
     */
    public static boolean deleteFile(File file) {
        boolean flag = false;
        if (file.exists() && file.isFile()) {
            file.delete();
            flag = true;
        }
        return flag;
    }
}

Related

  1. clearFilesOnPath(String path)
  2. clearFolder(File f)
  3. clearFolder(File[] children)
  4. clearFolder(String directoryLocation)
  5. clearFolder(String folder)
  6. clearFolderContent(String folderName)
  7. deepDelete(final File file)
  8. emptyAndDelete(File fileOrDir)
  9. emptyDerbyTestDirectory(final String derbyTestDirectory)