Java Delete File Recursively deleteRecursive(File dir)

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

Description

Deletes everything under a directory (including subdirectories)

License

Open Source License

Declaration

public static boolean deleteRecursive(File dir) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2006-2010 eBay Inc. 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
 *******************************************************************************/

import java.io.File;

public class Main {
    /**//from   w  ww  . j a  v  a 2 s . c  o  m
     * Deletes everything under a directory (including subdirectories)
     */
    public static boolean deleteRecursive(File dir) {

        if (!dir.exists()) {
            return true;
        }

        File tempFile;
        File[] fileList = dir.listFiles();
        int fileListLength = fileList.length;
        int index;
        boolean result = false;
        // use recursion to go through all the subdirectories and files and delete all of the files
        for (index = 0; index < fileListLength; index++) {
            tempFile = fileList[index];
            if (tempFile.isDirectory()) {
                deleteRecursive(tempFile);
            } else if (tempFile.isFile()) {
                result = tempFile.delete();
            }

        }
        // all the files are deleted, so now delete the directory skeleton
        result = dir.delete();
        return result;
    }

    /**
     * Deletes everything under a directory (including subdirectories)
     */
    public static void deleteRecursive(String dir) {
        deleteRecursive(new File(dir));
    }
}

Related

  1. deleteRec(File f)
  2. deleteRecursive(File dir)
  3. deleteRecursive(File dir)
  4. deleteRecursive(File dir)
  5. deleteRecursive(File dir)
  6. deleteRecursive(File f)
  7. deleteRecursive(File f)
  8. deleteRecursive(File f)
  9. deleteRecursive(File f)