Java Directory Clean cleanDir(String directory)

Here you can find the source of cleanDir(String directory)

Description

Empty a directory without deleting it

License

Open Source License

Parameter

Parameter Description
directory The directory to be cleaned

Return

true only if cleaning was successful

Declaration

public static boolean cleanDir(String directory) throws IOException 

Method Source Code


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

import java.io.*;

public class Main {
    /**/* w  w w  . j  a  v  a 2  s .  c o  m*/
     * Empty a directory without deleting it
     *
     * @param directory The directory to be cleaned
     * @return true only if cleaning was successful
     */
    public static boolean cleanDir(String directory) throws IOException {
        String[] files = ls(directory);
        boolean clean = true;
        // Some JVMs return null for empty dirs
        if (files != null) {
            for (String f : files) {
                String filename = directory + File.separator + f;
                File file = new File(filename);
                if (file.isDirectory())
                    clean = cleanDir(filename) && file.delete();
                else
                    clean = file.delete();
            }
        }
        return clean;
    }

    /**
     * List the contents of a directory.
     */
    public static String[] ls(String directory) throws IOException {
        if (!isDirectory(directory)) {
            throw new IOException("Invalid directory! " + directory);
        }

        return (new File(directory)).list();
    }

    /**
     * Check if the argument is a directory.
     */
    public static boolean isDirectory(String dir) {
        return (new File(dir)).isDirectory();
    }
}

Related

  1. cleanDir(final File dir)
  2. cleanDir(final File dir)
  3. cleanDir(final File dir, final String exclude)
  4. cleanDir(final String luceneDir)
  5. cleanDir(String dir)
  6. cleanDir(String path)
  7. cleanDirectory(File currentDir)
  8. cleanPath(String loc)
  9. cleanPath(String path)