Java Delete Directory deleteFiles(File dir)

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

Description

Deletes all files in a directory, but leaving the directory otherwise unmodified.

License

Open Source License

Parameter

Parameter Description
dir the directory to clean

Exception

Parameter Description
IOException if some files couldn't be deleted

Declaration

public static void deleteFiles(File dir) throws IOException 

Method Source Code


//package com.java2s;
/*/*from w w  w .j av  a  2 s  .  c om*/
 * RapidContext <http://www.rapidcontext.com/>
 * Copyright (c) 2007-2013 Per Cederberg. All rights reserved.
 *
 * This program is free software: you can redistribute it and/or
 * modify it under the terms of the BSD license.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 *
 * See the RapidContext LICENSE for more details.
 */

import java.io.File;

import java.io.IOException;

public class Main {
    /**
     * Deletes all files in a directory, but leaving the directory
     * otherwise unmodified. This function will delete any
     * sub-directories recursively.
     *
     * @param dir            the directory to clean
     *
     * @throws IOException if some files couldn't be deleted
     *
     * @see #delete(File)
     */
    public static void deleteFiles(File dir) throws IOException {
        if (dir != null && dir.isDirectory()) {
            File[] files = dir.listFiles();
            if (files != null) {
                for (int i = 0; i < files.length; i++) {
                    delete(files[i]);
                }
            }
        }
    }

    /**
     * Deletes a file or a directory. This function will delete all
     * files and sub-directories inside a directory recursively.
     *
     * @param file           the file or directory to delete
     *
     * @throws IOException if some files couldn't be deleted
     *
     * @see #deleteFiles(File)
     */
    public static void delete(File file) throws IOException {
        if (file != null && file.isDirectory()) {
            deleteFiles(file);
        }
        if (file != null && !file.delete()) {
            throw new IOException("failed to delete " + file);
        }
    }
}

Related

  1. deleteDirectoryContents(File directory)
  2. deleteDirectoryContents(File directory)
  3. deleteDirectoryContents(File directory)
  4. deleteDirectoryContents(final File dir)
  5. deleteDirectoryContents(final File dir, int deleteDirLevel, int level)
  6. deleteFiles(File dir)
  7. deleteFiles(File directory)
  8. deleteFiles(File directory)
  9. deleteFiles(File directory)