bb.io
Class DirUtil

java.lang.Object
  extended by bb.io.DirUtil

public final class DirUtil
extends Object

Provides static utility methods for dealing with directories.

This class is multithread safe: it is immutable (both its immediate state, as well as the deep state of its fields).

Author:
Brent Boyer
See Also:
FileUtil

Nested Class Summary
static class DirUtil.UnitTest
          See the Overview page of the project's javadocs for a general description of this unit test class.
 
Constructor Summary
private DirUtil()
          This sole private constructor suppresses the default (public) constructor, ensuring non-instantiability outside of this class.
 
Method Summary
static boolean areContentsSame(File directory1, File directory2)
          Determines whether or not the contents of directory1 and directory2 are identical.
static boolean contains(File directory, File file)
          Determines whether or not directory contains file (which could be either a normal file or a directory).
static void delete(File directory)
          Deletes a directory along with all of its contents.
static void deleteIfExists(File directory)
          Calls delete(directory) if directory !
static File ensureExists(File directory)
          Makes sure that directory exists, creating it and any parent directories if necessary.
protected static void erase(File directory, boolean deleteDirectory)
          Always deletes the contents of directory; the fate of the directory itself is specified by the deleteDirectory arg.
private static void exploreTree(File directory, FileFilter fileFilter, List<File> fileList, boolean sortResult, boolean restrictToNormalFiles)
           
static File findRootWithSpaceFreeMax()
          Returns that filesystem root directory which has the most free space.
static File[] getContents(File directory)
          Returns getContents(directory, null).
static File[] getContents(File directory, FileFilter fileFilter)
          Returns getContents(directory, fileFilter, true).
static File[] getContents(File directory, FileFilter fileFilter, boolean sortResult)
          Returns the contents of a directory.
static File[] getFilesInTree(File directory)
          Returns getFilesInTree(directory, null).
static File[] getFilesInTree(File directory, FileFilter fileFilter)
          Returns getFilesInTree(directory, fileFilter, true).
static File[] getFilesInTree(File directory, FileFilter fileFilter, boolean sortResult)
          Explores the tree rooted at directory and returns all the normal files that are accepted by fileFilter.
private static String getFullPath(File file)
          Returns a String that always starts with getCanonicalPath.
static File getTemp()
          Returns a new File representing the default temp directory (that is, the path returned by a call to System.getProperty("java.io.tmpdir")).
static File[] getTree(File directory)
          Returns getTree(directory, null).
static File[] getTree(File directory, FileFilter fileFilter)
          Returns getTree(directory, fileFilter, true).
static File[] getTree(File directory, FileFilter fileFilter, boolean sortResult)
          Explores the tree rooted at directory and returns all the Files (normal files, subdirectories, and other file system elements) that are accepted by fileFilter.
static File getWorking()
          Returns a new File representing the current working directory (that is, the path returned by a call to System.getProperty("user.dir")).
static void gut(File directory)
          Deletes only the contents of a directory; the directory itself will remain.
static void gutIfExists(File directory)
          Calls gut(directory) if directory !
static void rename(File directory1, File directory2)
          Trys to rename directory1 to directory2, and throws an IOException if the rename failed.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

DirUtil

private DirUtil()
This sole private constructor suppresses the default (public) constructor, ensuring non-instantiability outside of this class.

Method Detail

ensureExists

public static File ensureExists(File directory)
                         throws IllegalArgumentException,
                                SecurityException,
                                IllegalStateException
Makes sure that directory exists, creating it and any parent directories if necessary.

The usefulness of this method (compared to simply calling File.mkdirs) is:

  1. this method only calls File.mkdirs if directory fails to exist in the first place
  2. it checks that the call to File.mkdirs succeeded
  3. it checks that an actual directory was created, not some other type of file

Returns:
directory, which enables method call chaining
Throws:
IllegalArgumentException - if directory is null
SecurityException - if a security manager exists and does not permit verification of the existence of directory and all necessary parent directories; or if it does not permit directory and all necessary parent directories to be created
IllegalStateException - if directory failed to be created or is not an actual directory but is some other type of file

contains

public static boolean contains(File directory,
                               File file)
                        throws IllegalArgumentException,
                               SecurityException,
                               IOException
Determines whether or not directory contains file (which could be either a normal file or a directory).

For the purposes of this method, "contains" means "equals or is found inside". Consequently, this method returns true if directory equals file.

This method works correctly regardless of whether directory or file were initially specified as relative, absolute, or canonical paths because it first internally converts them both to canonical paths.

Warning: directory must actually exist, since a call will be made to its isDirectory method. In contrast, file need not actually exist.

Parameters:
directory - an existing filesystem directory
file - an arbitrary filesystem path that need not exist nor and which can resolve to either a normal file or directory
Throws:
IllegalArgumentException - if directory is not valid; file == null
SecurityException - if a security manager exists and denies read access to directory
IOException - if an I/O problem occurs

getFullPath

private static String getFullPath(File file)
                           throws IOException
Returns a String that always starts with getCanonicalPath. If file is a directory, then further ensures that the result ends with File.separatorChar.

This method was written to support the path comparison logic inside contains(java.io.File, java.io.File) because getCanonicalPath does not guarantee the above behavior for directories.

To see why this behavior is critical for the logic inside the current implementation of contains, consider the case that on some platform getCanonicalPath returns "a/b/someName" for directory and "a/b/someNamePlusMore" for file: if simply used getCanonicalPath for the path determination, would wrongly return true but if use this method, will correctly return false.

Throws:
IOException

findRootWithSpaceFreeMax

public static File findRootWithSpaceFreeMax()
Returns that filesystem root directory which has the most free space.

Contract: the result is always a valid directory


getTemp

public static File getTemp()
                    throws RuntimeException
Returns a new File representing the default temp directory (that is, the path returned by a call to System.getProperty("java.io.tmpdir")).

Throws:
RuntimeException - (or some subclass) if any problem occurs

getWorking

public static File getWorking()
                       throws RuntimeException
Returns a new File representing the current working directory (that is, the path returned by a call to System.getProperty("user.dir")).

Throws:
RuntimeException - (or some subclass) if any problem occurs

getContents

public static File[] getContents(File directory)
                          throws IllegalArgumentException,
                                 SecurityException,
                                 IOException
Returns getContents(directory, null).

Throws:
IllegalArgumentException
SecurityException
IOException

getContents

public static File[] getContents(File directory,
                                 FileFilter fileFilter)
                          throws IllegalArgumentException,
                                 SecurityException,
                                 IOException
Returns getContents(directory, fileFilter, true).

Throws:
IllegalArgumentException
SecurityException
IOException

getContents

public static File[] getContents(File directory,
                                 FileFilter fileFilter,
                                 boolean sortResult)
                          throws IllegalArgumentException,
                                 SecurityException,
                                 IOException
Returns the contents of a directory.

The usefulness of this method, compared to the File.listFiles methods, is:

  1. first checks that directory is valid
  2. guarantees that the result returned is non-null (tho may be zero length)
  3. can specify that the result is to be sorted in ascending order
  4. handles some operating system specific bugs

Parameters:
directory - a File for the directory whose contents are to be retrieved
fileFilter - restricts what appears in the result; may be null, in which case no filtering is done
sortResult - specifies whether or not the result should be sorted in ascending order (if false, the order is unspecified)
Throws:
IllegalArgumentException - if directory is not valid
SecurityException - if a security manager exists and denies read access to some file
IOException - if an I/O problem occurs

getTree

public static File[] getTree(File directory)
                      throws IllegalArgumentException,
                             SecurityException,
                             IOException
Returns getTree(directory, null).

Throws:
IllegalArgumentException
SecurityException
IOException

getTree

public static File[] getTree(File directory,
                             FileFilter fileFilter)
                      throws IllegalArgumentException,
                             SecurityException,
                             IOException
Returns getTree(directory, fileFilter, true).

Throws:
IllegalArgumentException
SecurityException
IOException

getTree

public static File[] getTree(File directory,
                             FileFilter fileFilter,
                             boolean sortResult)
                      throws IllegalArgumentException,
                             SecurityException,
                             IOException
Explores the tree rooted at directory and returns all the Files (normal files, subdirectories, and other file system elements) that are accepted by fileFilter.

Subdirectories are handled as follows:

  1. if a subdirectory is accepted by fileFilter, then not only is it present in the result, but its contents are recursively explored depth first for further elements in the result
  2. if a subdirectory is rejected by fileFilter, then not only is it absent from the result, but its contents are unexplored
Consequently, be careful about supplying a FileFilter that always rejects directories (e.g. JavaFilter), since that will prevent subdirectory exploration (unless that is a desird effect).

Contract: the result is never null, and is guaranteed to be sorted in ascending order if sortResult is true.

Parameters:
directory - a File for the directory whose tree files are to be retrieved
fileFilter - a java.io.FileFilter instance for filtering the returned result; may be null (i.e. no filtering is done); note that if fileFilter rejects a subdirectory, then that entire subtree is excluded
sortResult - specifies whether or not the result should be sorted in ascending order (if false, the order returned is unspecified)
Throws:
IllegalArgumentException - if directory is null, non-existent, or is not an actual directory
SecurityException - if a security manager exists and denies read access to some file
IOException - if an I/O problem occurs

getFilesInTree

public static File[] getFilesInTree(File directory)
                             throws IllegalArgumentException,
                                    SecurityException,
                                    IOException
Returns getFilesInTree(directory, null).

Throws:
IllegalArgumentException
SecurityException
IOException

getFilesInTree

public static File[] getFilesInTree(File directory,
                                    FileFilter fileFilter)
                             throws IllegalArgumentException,
                                    SecurityException,
                                    IOException
Returns getFilesInTree(directory, fileFilter, true).

Throws:
IllegalArgumentException
SecurityException
IOException

getFilesInTree

public static File[] getFilesInTree(File directory,
                                    FileFilter fileFilter,
                                    boolean sortResult)
                             throws IllegalArgumentException,
                                    SecurityException,
                                    IOException
Explores the tree rooted at directory and returns all the normal files that are accepted by fileFilter.

Subdirectories are unaffected by fileFilter: they are always absent from the result, however, they are always recursively examined depth first.

Contract: the result is never null, and is guaranteed to be sorted in ascending order if sortResult is true.

Parameters:
directory - a File for the directory whose tree files are to be retrieved
fileFilter - a java.io.FileFilter instance for filtering the returned result; may be null (i.e. no filtering is done); note that if fileFilter rejects a subdirectory, then that entire subtree is excluded
sortResult - specifies whether or not the result should be sorted in ascending order (if false, the order returned is unspecified)
Throws:
IllegalArgumentException - if directory is null, non-existent, or is not an actual directory
SecurityException - if a security manager exists and denies read access to some file
IOException - if an I/O problem occurs

exploreTree

private static void exploreTree(File directory,
                                FileFilter fileFilter,
                                List<File> fileList,
                                boolean sortResult,
                                boolean restrictToNormalFiles)
                         throws IllegalArgumentException,
                                SecurityException,
                                IOException
Throws:
IllegalArgumentException
SecurityException
IOException

areContentsSame

public static boolean areContentsSame(File directory1,
                                      File directory2)
                               throws IllegalArgumentException,
                                      SecurityException,
                                      IOException
Determines whether or not the contents of directory1 and directory2 are identical.

The sorted contents of both directory1 and directory2 are retrieved using getContents(File). False is immediately returned if the sizes differ. Otherwise, both SortedSets are simultaneously iterated thru and each corresponding element is compared for equality. (This works, because even tho they have different roots, identical trees will nevertheless have the same paths relative to each root.) False is returned if ever a pair have different names or types. (The types are directories, normal files, and "other" file system elements.) If both are directories, then this method is recursively called to see if they differ. If both are normal files, they must be byte for byte identical, which may require a deep file examination to confirm.

Throws:
IllegalArgumentException - if directory1 or directory2 are not valid
SecurityException - if a security manager exists and denies read access to either directory
IOException - if an I/O problem occurs

delete

public static void delete(File directory)
                   throws IllegalArgumentException,
                          SecurityException,
                          IOException
Deletes a directory along with all of its contents. It is useful because the delete method of File fails if the directory has any content.

Note: FileUtil.delete should be used to delete a normal file.

Parameters:
directory - a File for the directory that is to be deleted
Throws:
IllegalArgumentException - if directory is not valid
SecurityException - if a security manager exists and denies read access to some file
IOException - if an I/O problem occurs

deleteIfExists

public static void deleteIfExists(File directory)
                           throws IllegalArgumentException,
                                  SecurityException,
                                  IOException
Calls delete(directory) if directory != null and directory exists.

Note: FileUtil.deleteIfExists should be used to delete a normal file if it exists.

Parameters:
directory - a File for the directory that is to be deleted; may be null or non-existent
Throws:
IllegalArgumentException - if directory is not null but is not valid
SecurityException - if a security manager exists and denies read access to some file
IOException - if an I/O problem occurs; this includes failure of the directory to be deleted

gut

public static void gut(File directory)
                throws IllegalArgumentException,
                       SecurityException,
                       IOException
Deletes only the contents of a directory; the directory itself will remain. It is useful because the File class has no such method.

Parameters:
directory - a File for the directory whose contents are to be deleted
Throws:
IllegalArgumentException - if directory is not valid
SecurityException - if a security manager exists and denies read access to some file
IOException - if an I/O problem occurs

gutIfExists

public static void gutIfExists(File directory)
                        throws IllegalArgumentException,
                               SecurityException,
                               IOException
Calls gut(directory) if directory != null and directory exists.

Note: FileUtil.deleteIfExists should be used to delete a normal file if it exists.

Parameters:
directory - the directory that is to be gutted; may be null or non-existent
Throws:
IllegalArgumentException - if directory is not null but is not valid
SecurityException - if a security manager exists and denies read access to some file
IOException - if an I/O problem occurs

erase

protected static void erase(File directory,
                            boolean deleteDirectory)
                     throws IllegalArgumentException,
                            SecurityException,
                            IOException
Always deletes the contents of directory; the fate of the directory itself is specified by the deleteDirectory arg. This method is useful because the File class has no such method.

This method marches down the directory tree depth first, deleting all normal files, and then deleting directories as they become empty.

Parameters:
directory - a File for the directory whose contents are to be deleted
Throws:
IllegalArgumentException - if directory is null, non-existent, or is not an actual directory
SecurityException - if a security manager exists and denies read access to some file
IOException - if an I/O problem occurs

rename

public static void rename(File directory1,
                          File directory2)
                   throws IllegalArgumentException,
                          SecurityException,
                          IOException
Trys to rename directory1 to directory2, and throws an IOException if the rename failed. It is useful because File.renameTo unfortunately merely returns a boolean indicating the success of the operation, rather than throwing an Exception.

Note: FileUtil.rename should be used to rename normal files.

Parameters:
directory1 - the currently existing directory
directory2 - the directory that is to be renamed to
Throws:
IllegalArgumentException - if directory1 is not valid; directory2 == null or already exists
SecurityException - if a security manager exists and denies write access to directory1 or directory2
IOException - if an I/O problem occurs; this includes failure of the directory to be renamed