Java Folder Delete nio deleteRecursively(File folder)

Here you can find the source of deleteRecursively(File folder)

Description

Recursively deletes a folder and all its content

License

Mozilla Public License

Parameter

Parameter Description
folder a parameter

Exception

Parameter Description
IOException an exception

Declaration

public static void deleteRecursively(File folder) throws IOException 

Method Source Code

//package com.java2s;
/***************************** BEGIN LICENSE BLOCK ***************************
    // w  w w. ja  v  a  2 s .c o m
The contents of this file are subject to the Mozilla Public License, v. 2.0.
If a copy of the MPL was not distributed with this file, You can obtain one
at http://mozilla.org/MPL/2.0/.
    
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
for the specific language governing rights and limitations under the License.
     
Copyright (C) 2012-2015 Sensia Software LLC. All Rights Reserved.
     
******************************* END LICENSE BLOCK ***************************/

import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;

public class Main {
    /**
     * Recursively deletes a folder and all its content
     * @param folder
     * @throws IOException
     */
    public static void deleteRecursively(File folder) throws IOException {
        Files.walkFileTree(folder.toPath(), new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException {
                if (e == null) {
                    Files.delete(dir);
                    return FileVisitResult.CONTINUE;
                } else {
                    throw e;
                }
            }

            @Override
            public FileVisitResult visitFile(Path f, BasicFileAttributes att) throws IOException {
                Files.delete(f);
                return FileVisitResult.CONTINUE;
            }

        });
    }
}

Related

  1. deleteEmptyFolder(String... dirNames)
  2. deleteFile(String folderName, String fileName)
  3. deleteFolder(Path folder)
  4. deleteFolder(Path path)
  5. deleteFolderAndSubfolders(Path pathToFile)