Java Delete Directory deleteFilesFromDirectory(final String dirNameIn, final String filePrefixIn)

Here you can find the source of deleteFilesFromDirectory(final String dirNameIn, final String filePrefixIn)

Description

Deletes all files in the directory but not the directory itself

License

Open Source License

Parameter

Parameter Description
dirNameIn a parameter
filePrefixIn Null to delete all files or the prefix of the files to delete

Return

True if all files were deleted

Declaration

public static boolean deleteFilesFromDirectory(final String dirNameIn, final String filePrefixIn) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.io.File;

public class Main {
    /**/*from   w  ww  .ja  v  a  2 s .c om*/
     * Deletes all files in the directory but not the directory itself
     * @param dirNameIn
     * @param filePrefixIn Null to delete all files or the prefix of the files to delete
     * @return True if all files were deleted
     */
    public static boolean deleteFilesFromDirectory(final String dirNameIn, final String filePrefixIn) {

        boolean fileNotDeleted = false;
        String filePrefix = filePrefixIn;
        if (filePrefix != null) {
            filePrefix = filePrefix.toUpperCase();
        }
        File dir = new File(dirNameIn);

        if (dir.isDirectory() == false) {
            throw new IllegalArgumentException("Specified path [" + dirNameIn + "] is not a directory");
        }

        if (dir.exists()) {
            String[] children = dir.list();
            if (children != null) {
                for (int i = 0; i < children.length; i++) {
                    String fileName = children[i];
                    if (filePrefix == null || fileName.toUpperCase().startsWith(filePrefix)) {
                        File f = new File(dir, children[i]);
                        if (f.isFile()) {
                            if (f.delete() == false) {
                                fileNotDeleted = true;
                            }
                        }
                    }
                }
            }
        }
        return (fileNotDeleted == false);

    }

    public static boolean isDirectory(String path) {
        File f = new File(path);
        return (f.exists() && f.isDirectory());
    }
}

Related

  1. deleteFiles(String root, String mask)
  2. deleteFiles(String sDir, String sSearch)
  3. deleteFiles(String[] filenames)
  4. deleteFilesAndDir(List files)
  5. deleteFilesAndSubDirs(File dir)
  6. deleteFilesInDir(File dir)
  7. deleteFilesInDir(File dir)