Remove file or directory : Delete « File « Java Tutorial






/* 
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
 */

import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 
 * FileUtils is a collection of routines for common file system operations.
 * 
 * @author Dan Jemiolo (danj)
 * 
 */

public final class FileUtils {

  /**
   * 
   * Starts at the directory given and tests to see whether it is empty; if so,
   * it deletes it and moves up the directory tree, deleting empty directories
   * until it finds a non-empty one.
   * 
   * @param directory
   *          The first directory to test.
   * 
   * @throws IOException
   *           <ul>
   *           <li>If the directory does not exist or the user does not have
   *           permission to delete it or its parents.</li>
   *           </ul>
   * 
   */
  public static void pruneEmptyDirectories(File directory) throws IOException {
    if (directory == null)
      throw new NullPointerException("NullFile");

    if (!directory.isDirectory()) {
      Object[] filler = { directory.getAbsolutePath() };
      String message = "NotDirectory";
      throw new IllegalArgumentException(message);
    }

    //
    // check to see if the directory is now empty and, if so, delete it
    // too, moving up the tree until we find one with stuff in it
    //
    while (directory != null) {
      File[] directoryFiles = directory.listFiles();

      //
      // if the directory has files, we're done
      //
      if (directoryFiles.length > 0)
        break;

      if (!directory.delete()) {
        Object[] filler = { directory.getAbsolutePath() };
        String message = "DeleteFailed";
        throw new IOException(message);
      }

      //
      // go up the tree
      //
      directory = directory.getParentFile();
    }
  }

  /**
   * 
   * The application's current working directory.
   * 
   */
  public static final File CURRENT_DIR = new File(".");


  /**
   * 
   * This is a convenience method that calls remove(File, boolean) with the
   * second parameter set to "false" (doesn't prune empty directories).
   * 
   * @see #remove(File, boolean)
   * 
   */
  public static void remove(File file) throws IOException {
    remove(file, false);
  }

  /**
   * 
   * @param file
   *          The file or directory to delete.
   * 
   * @param pruneEmptyDirectories
   *          True if the deletion results in an empty parent directory. If set
   *          to true, this method will traverse up the directory tree, deleting
   *          directories that are made empty by the deletion.
   * 
   * @throws IOException
   *           <ul>
   *           <li>If there was an error trying to remove the file or
   *           directory. The file system may be in an inconsistent state when
   *           the exception is thrown (directories may be partially deleted,
   *           etc.).</li>
   *           </ul>
   * 
   */
  public static void remove(File file, boolean pruneEmptyDirectories) throws IOException {
    if (file == null)
      throw new NullPointerException("NullFile");

    if (file.isDirectory())
      removeDirectory(file);

    else
      removeFile(file);

    if (pruneEmptyDirectories)
      pruneEmptyDirectories(file.getParentFile());
  }

  private static void removeDirectory(File directory) throws IOException {
    File[] files = directory.listFiles();

    //
    // for all items in the directory...
    //
    for (int n = 0; n < files.length; ++n) {
      File nextFile = files[n];

      //
      // if it's a directory, delete sub-directories and files before
      // removing the empty directory
      //
      if (nextFile.isDirectory())
        removeDirectory(nextFile);

      //
      // otherwise just delete the file - do NOT prune the directory
      // in advance
      //
      else
        removeFile(nextFile);
    }

    //
    // now that everything's gone, delete the specified directory
    //
    if (!directory.delete()) {
      Object[] filler = { directory.getAbsolutePath() };
      String message = "DeleteFailed";
      throw new IOException(message);
    }
  }

  private static void removeFile(File file) throws IOException {
    //
    // make sure the file exists, then delete it
    //

    if (!file.exists())
      throw new FileNotFoundException(file.getAbsolutePath());

    if (!file.delete()) {
      Object[] filler = { file.getAbsolutePath() };
      String message = "DeleteFailed";
      throw new IOException(message);
    }
  }
}








11.79.Delete
11.79.1.Deletes the diretory and any files and directories in it recursively.
11.79.2.Delete the file or non-empty directory at the supplied path
11.79.3.Delete all files under this file and including this file
11.79.4.Deletes a directory.
11.79.5.Empty and delete a folder (and subfolders).
11.79.6.Recursive directory deletion
11.79.7.Recursively delete a file and all its contents
11.79.8.Recursivly delete directory
11.79.9.Remove file or directory
11.79.10.Remove a directory and all of its contents.
11.79.11.Deletes all files and subdirectories