Starts at the directory given and tests to see whether it is empty : Directory « File Input Output « Java






Starts at the directory given and tests to see whether it is empty

      
/* 
 * 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);
    }
  }
}

   
    
    
    
    
    
  








Related examples in the same category

1.Create directory
2.Create directory along with required nonexistent parent directories
3.Create directory tree (nested/cascade folders)
4.Create a directories recursively
5.Copying a Directory: Copies files under srcDir to dstDir, if dstDir does not exist, it will be created.
6.Delete a non-empty directory: Deletes all files and subdirectories under dir.
7.Listing the Files or Subdirectories in a Directory
8.Listing the File System Roots
9.The Directory Listing ApplicationThe Directory Listing Application
10.use list( ) to examine the contents of a directory:
11.Reading and Printing a Directory HierarchyReading and Printing a Directory Hierarchy
12.Display a file system in a JTree viewDisplay a file system in a JTree view
13.File Tree DemoFile Tree Demo
14.File Table HTMLFile Table HTML
15.A standalone program that deletes a specified file or directory
16.Get Last modification time of a file or directory
17.Set last modified time of a file or directory
18.List contents of a directory
19.Determine if file or directory exists
20.Determine if File or Directory is hidden
21.Check if a directory is not empty
22.Get name of parent directory
23.Get name of specified file or directory
24.Get current directory
25.Mark file or directory Read Only
26.Rename file or directory
27.Traversing all files and directories under dir
28.Traversing only directories under dir
29.Traversing only files under dir
30.Creates and displays a window containing a list of files and sub-directories in a specified directory
31.Calculate directory size
32.Delete directory recursively
33.Determining If Two Filename Paths Refer to the Same File
34.Recursive directory deletion
35.Recursivly delete directory
36.Searches through the directory tree
37.Directory Walker
38.Utility methods for handling files and directories
39.Creates a new and empty directory in the default temp directory using the given prefix.
40.Count files in a directory (including files in all subdirectories)
41.Create a unique directory within a directory 'root'
42.Creates a new empty temporary directory.
43.Get Files Recurse
44.Recursively search a directory tree
45.Find directoriesFind directories