Java Directory Clean cleanDir(File dir)

Here you can find the source of cleanDir(File dir)

Description

Cleans a directory, deleting all of its contents.

License

Apache License

Parameter

Parameter Description
dir The directory.

Declaration

public static void cleanDir(File dir) 

Method Source Code

//package com.java2s;
// Licensed under the Apache License, Version 2.0 (the "License");

import java.io.File;

public class Main {
    /**/*from  w w  w . j  ava2  s .c  o  m*/
     * Cleans a directory, deleting all of its contents. <br />
     * <br />
     * 
     * The directory itself will not be deleted.
     * 
     * @param dir
     *            The directory.
     */
    public static void cleanDir(File dir) {
        if (!dir.isDirectory()) {
            throw new IllegalStateException("Directory does not exist: " + dir);
        }
        for (File file : dir.listFiles()) {
            deleteFile(file);
        }
    }

    /**
     * Deletes a file or directory.
     * 
     * @param file
     *            The file or directory.
     */
    public static void deleteFile(File file) {
        if (file.exists()) {
            if (file.isDirectory()) {
                for (File child : file.listFiles()) {
                    deleteFile(child);
                }
            }
            boolean deleted = file.delete();
            if (!deleted) {
                throw new IllegalStateException("Could not delete file or directory: " + file);
            }
        }
    }
}

Related

  1. cleanDir(File dir)
  2. cleanDir(File directory)
  3. cleanDir(final File dir)
  4. cleanDir(final File dir)
  5. cleanDir(final File dir, final String exclude)