Java File Delete delete(File file)

Here you can find the source of delete(File file)

Description

Recursively delete starting at the given file.

License

Open Source License

Declaration

public static boolean delete(File file) throws Exception 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2013 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:/*from  w  w w. j  a  va 2 s  .c o  m*/
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/

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

public class Main {
    /**
      * Recursively delete starting at the given file.
      */
    public static boolean delete(File file) throws Exception {
        // paranoia check... Don't delete root directory because somehow the path was empty
        if (file.getParent() == null) {
            return false;
        }
        return deleteUsingJavaIO(file);
    }

    private static boolean deleteUsingJavaIO(File file) throws IOException {
        // take into account file or its children may be valid symbolic links.
        // we do not want to follow them.
        // The alternative to this is to use EFS to do the delete which does
        // essentially the same thing.
        // The other alternative is to use EFS to get the attributes and see
        // if it is a symbolic link and tailor the delete according to that.
        // This may have incorrect behaviour if the file is a link
        // and read-only.
        if (file.delete() || !file.exists()) {
            // Try to delete the file/link first without recursing to avoid
            // traversing into links
            return true;
        }
        if (file.isDirectory()) {
            File[] children = file.listFiles();
            if (children != null) {
                for (File child : children) {
                    deleteUsingJavaIO(child);
                }
            }
        }
        return file.delete();
    }
}

Related

  1. delete(File file)
  2. delete(File file)
  3. delete(File file)
  4. delete(File file)
  5. delete(File file)
  6. delete(File file)
  7. delete(File file)
  8. delete(File file)
  9. delete(File file)