Java File Path Delete deleteDir(File dir)

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

Description

delete Dir

License

Apache License

Declaration

private static void deleteDir(File dir) 

Method Source Code


//package com.java2s;
/*//from  w ww . ja  v  a  2s .c  o  m
 * Copyright 2015 Red Hat, Inc. and/or its affiliates.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * 
 *      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.
 * See the License for the specific language governing permissions and
 * limitations under the License.
*/

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

public class Main {
    private static void deleteDir(File dir) {
        // Will throw RuntimeException is anything fails to delete
        String[] children = dir.list();
        for (String child : children) {
            File file = new File(dir, child);
            if (file.isFile()) {
                deleteFile(file);
            } else {
                deleteDir(file);
            }
        }

        deleteFile(dir);
    }

    private static void deleteFile(File file) {
        // This will attempt to delete a file 5 times, calling GC and Sleep between each iteration
        // Sometimes windows takes a while to release a lock on a file.
        // Throws an exception if it fails to delete
        if (!file.delete()) {
            int count = 0;
            while (!file.delete() && count++ < 5) {
                System.gc();
                try {
                    Thread.sleep(250);
                } catch (InterruptedException e) {
                    throw new RuntimeException("This should never happen");
                }
            }
        }

        if (file.exists()) {
            try {
                throw new RuntimeException("Unable to delete file:" + file.getCanonicalPath());
            } catch (IOException e) {
                throw new RuntimeException("Unable to delete file", e);
            }
        }
    }
}

Related

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