Java Directory Clear cleanDirectory(File dir, boolean deleteDirectory)

Here you can find the source of cleanDirectory(File dir, boolean deleteDirectory)

Description

Cleans up the dir and deletes it.

License

Open Source License

Parameter

Parameter Description
dir the directory to be cleaned up and deleted.
deleteDirectory if true , the directory is deleted too.

Exception

Parameter Description
IOException an exception

Return

true if the delete was successful . false otherwise

Declaration

static boolean cleanDirectory(File dir, boolean deleteDirectory) throws IOException 

Method Source Code

//package com.java2s;
/**/*  w ww.j a  v a 2  s.com*/
 * Copyright 2016 LinkedIn Corp. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 */

import java.io.File;
import java.io.IOException;

public class Main {
    /**
     * Cleans up the {@code dir} and deletes it.
     * @param dir the directory to be cleaned up and deleted.
     * @param deleteDirectory if {@code true}, the directory is deleted too.
     * @return {@code true if the delete was successful}. {@code false} otherwise
     * @throws IOException
     */
    static boolean cleanDirectory(File dir, boolean deleteDirectory) throws IOException {
        if (!dir.exists()) {
            return true;
        }
        if (!dir.isDirectory()) {
            throw new IllegalArgumentException(dir.getAbsolutePath() + " is not a directory");
        }
        File[] files = dir.listFiles();
        if (files == null) {
            throw new IOException("Could not list files in directory: " + dir.getAbsolutePath());
        }
        boolean success = true;
        for (File file : files) {
            success = file.delete() && success;
        }
        return deleteDirectory ? dir.delete() && success : success;
    }
}

Related

  1. cleanDirectory(File dir)
  2. cleanDirectory(File dir)
  3. cleanDirectory(File dir)
  4. cleanDirectory(File dir)
  5. cleanDirectory(File dir)
  6. cleanDirectory(File directory)
  7. cleanDirectory(File directory)
  8. cleanDirectory(File directory)
  9. cleanDirectory(File directory)