org.apache.commons.io
Class FileUtils

java.lang.Object
  extended byorg.apache.commons.io.FileUtils

public class FileUtils
extends java.lang.Object

This class provides basic facilities for manipulating files.

File-related methods

There are methods to create a File from a URL, copy a File to a directory, copy a File to another File, copy a URL's contents to a File, as well as methods to delete and clean a directory.

Common File manipulation routines.

Origin of code

Version:
$Id: FileUtils.java,v 1.39 2004/10/29 21:34:56 bayard Exp $
Author:
Kevin A. Burton, Scott Sanders, Daniel Rall, Christoph.Reck, Peter Donald, Jeff Turner, Matthew Hawthorne, Jeremias Maerki

Field Summary
static java.io.File[] EMPTY_FILE_ARRAY
          An empty array of type File.
static long ONE_GB
          The number of bytes in a gigabyte.
static long ONE_KB
          The number of bytes in a kilobyte.
static long ONE_MB
          The number of bytes in a megabyte.
 
Constructor Summary
FileUtils()
          Instances should NOT be constructed in standard programming.
 
Method Summary
static java.lang.String byteCountToDisplaySize(long size)
          Returns a human-readable version of the file size (original is in bytes).
static void cleanDirectory(java.io.File directory)
          Clean a directory without deleting it.
private static void cleanDirectoryOnExit(java.io.File directory)
          Clean a directory without deleting it.
static boolean contentEquals(java.io.File file1, java.io.File file2)
          Compare the contents of two files to determine if they are equal or not.
static java.io.File[] convertFileCollectionToFileArray(java.util.Collection files)
          Converts a Collection containing java.io.File instanced into array representation.
static void copyFile(java.io.File source, java.io.File destination)
          Copy file from source to destination.
static void copyFile(java.io.File source, java.io.File destination, boolean preserveFileDate)
          Copy file from source to destination.
static void copyFileToDirectory(java.io.File source, java.io.File destinationDirectory)
          Copy file from source to destination.
static void copyURLToFile(java.net.URL source, java.io.File destination)
          Copies bytes from the URL source to a file destination.
static void deleteDirectory(java.io.File directory)
          Recursively delete a directory.
private static void deleteDirectoryOnExit(java.io.File directory)
          Recursively schedule directory for deletion on JVM exit.
static void forceDelete(java.io.File file)
           Delete a file.
static void forceDeleteOnExit(java.io.File file)
          Schedule a file to be deleted when JVM exits.
static void forceMkdir(java.io.File directory)
          Make a directory.
private static void innerListFiles(java.util.Collection files, java.io.File directory, IOFileFilter filter)
          Finds files within a given directory (and optionally its subdirectories).
static boolean isFileNewer(java.io.File file, java.util.Date date)
          Tests if the specified File is newer than the specified Date.
static boolean isFileNewer(java.io.File file, java.io.File reference)
          Tests if the specified File is newer than the reference File.
static boolean isFileNewer(java.io.File file, long timeMillis)
          Tests if the specified File is newer than the specified time reference.
static java.util.Collection listFiles(java.io.File directory, IOFileFilter fileFilter, IOFileFilter dirFilter)
          Finds files within a given directory (and optionally its subdirectories).
static java.util.Collection listFiles(java.io.File directory, java.lang.String[] extensions, boolean recursive)
          Finds files within a given directory (and optionally its subdirectories) which match an array of extensions.
static byte[] readFileToByteArray(java.io.File file)
           Reads the contents of a file into a byte array.
static java.lang.String readFileToString(java.io.File file, java.lang.String encoding)
           Reads the contents of a file into a String.
static long sizeOfDirectory(java.io.File directory)
          Recursively count size of a directory (sum of the length of all files).
static java.io.File toFile(java.net.URL url)
          Convert from a URL to a File.
static java.io.File[] toFiles(java.net.URL[] urls)
          Converts each of an array of URL to a File.
private static java.lang.String[] toSuffixes(java.lang.String[] extensions)
          Converts an array of file extensions to suffixes for use with IOFileFilters.
static void touch(java.io.File file)
          Implements the same behaviour as the "touch" utility on Unix.
static java.net.URL[] toURLs(java.io.File[] files)
          Converts each of an array of File to a URL.
static boolean waitFor(java.io.File file, int seconds)
          Waits for NFS to propagate a file creation, imposing a timeout.
static void writeByteArrayToFile(java.io.File file, byte[] data)
           Writes a byte array to a file creating the file if it does not exist.
static void writeStringToFile(java.io.File file, java.lang.String data, java.lang.String encoding)
           Writes a String to a file creating the file if it does not exist.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

ONE_KB

public static final long ONE_KB
The number of bytes in a kilobyte.

See Also:
Constant Field Values

ONE_MB

public static final long ONE_MB
The number of bytes in a megabyte.

See Also:
Constant Field Values

ONE_GB

public static final long ONE_GB
The number of bytes in a gigabyte.

See Also:
Constant Field Values

EMPTY_FILE_ARRAY

public static final java.io.File[] EMPTY_FILE_ARRAY
An empty array of type File.

Constructor Detail

FileUtils

public FileUtils()
Instances should NOT be constructed in standard programming.

Method Detail

byteCountToDisplaySize

public static java.lang.String byteCountToDisplaySize(long size)
Returns a human-readable version of the file size (original is in bytes).

Parameters:
size - The number of bytes.
Returns:
A human-readable display value (includes units).

touch

public static void touch(java.io.File file)
                  throws java.io.IOException
Implements the same behaviour as the "touch" utility on Unix. It creates a new file with size 0 or, if the file exists already, it is opened and closed without modifying it, but updating the file date and time.

Parameters:
file - the File to touch
Throws:
java.io.IOException - If an I/O problem occurs

innerListFiles

private static void innerListFiles(java.util.Collection files,
                                   java.io.File directory,
                                   IOFileFilter filter)

Finds files within a given directory (and optionally its subdirectories). All files found are filtered by an IOFileFilter.

Parameters:
files - the collection of files found.
directory - the directory to search in.
filter - the filter to apply to files and directories.

convertFileCollectionToFileArray

public static java.io.File[] convertFileCollectionToFileArray(java.util.Collection files)
Converts a Collection containing java.io.File instanced into array representation. This is to account for the difference between File.listFiles() and FileUtils.listFiles().

Parameters:
files - a Collection containing java.io.File instances
Returns:
an array of java.io.File

listFiles

public static java.util.Collection listFiles(java.io.File directory,
                                             IOFileFilter fileFilter,
                                             IOFileFilter dirFilter)

Finds files within a given directory (and optionally its subdirectories). All files found are filtered by an IOFileFilter.

If your search should recurse into subdirectories you can pass in an IOFileFilter for directories. You don't need to bind a DirectoryFileFilter (via logical AND) to this filter. This method does that for you.

An example: If you want to search through all directories called "temp" you pass in FileFilterUtils.NameFileFilter("temp")

Another common usage of this method is find files in a directory tree but ignoring the directories generated CVS. You can simply pass in FileFilterUtils.makeCVSAware(null).

Parameters:
directory - the directory to search in
fileFilter - filter to apply when finding files.
dirFilter - optional filter to apply when finding subdirectories. If this parameter is null, subdirectories will not be included in the search. Use TrueFileFilter.INSTANCE to match all directories.
Returns:
an collection of java.io.File with the matching files
See Also:
FileFilterUtils, NameFileFilter

toSuffixes

private static java.lang.String[] toSuffixes(java.lang.String[] extensions)
Converts an array of file extensions to suffixes for use with IOFileFilters.

Parameters:
extensions - an array of extensions. Format: {"java", "xml"}
Returns:
an array of suffixes. Format: {".java", ".xml"}

listFiles

public static java.util.Collection listFiles(java.io.File directory,
                                             java.lang.String[] extensions,
                                             boolean recursive)
Finds files within a given directory (and optionally its subdirectories) which match an array of extensions.

Parameters:
directory - the directory to search in
extensions - an array of extensions, ex. {"java","xml"}. If this parameter is null, all files are returned.
recursive - If true all subdirectories are searched, too.
Returns:
an collection of java.io.File with the matching files

contentEquals

public static boolean contentEquals(java.io.File file1,
                                    java.io.File file2)
                             throws java.io.IOException

Compare the contents of two files to determine if they are equal or not.

Code origin: Avalon

Parameters:
file1 - the first file
file2 - the second file
Returns:
true if the content of the files are equal or they both don't exist, false otherwise
Throws:
java.io.IOException - in case of an I/O error

toFile

public static java.io.File toFile(java.net.URL url)
Convert from a URL to a File.

Parameters:
url - the file URL to convert
Returns:
the equivalent File object, or null if the URL's protocol is not file

toFiles

public static java.io.File[] toFiles(java.net.URL[] urls)
Converts each of an array of URL to a File.

Returns an array of the same size as the input. If the input is null, an empty array is returned. If the input contains null, the output array contains null at the same index.

Parameters:
urls - the file URLs to convert, null returns empty array
Returns:
a non-null array of Files matching the input, with a null item if there was a null at that index in the input array

toURLs

public static java.net.URL[] toURLs(java.io.File[] files)
                             throws java.io.IOException
Converts each of an array of File to a URL.

Returns an array of the same size as the input.

Parameters:
files - the files to convert
Returns:
an array of URLs matching the input
Throws:
java.io.IOException - if a file cannot be converted

copyFileToDirectory

public static void copyFileToDirectory(java.io.File source,
                                       java.io.File destinationDirectory)
                                throws java.io.IOException
Copy file from source to destination. If destinationDirectory does not exist, it (and any parent directories) will be created. If a file source in destinationDirectory exists, it will be overwritten. The copy will have the same file date as the original.

Parameters:
source - An existing File to copy.
destinationDirectory - A directory to copy source into.
Throws:
java.io.FileNotFoundException - if source isn't a normal file.
java.lang.IllegalArgumentException - if destinationDirectory isn't a directory.
java.io.IOException - if source does not exist, the file in destinationDirectory cannot be written to, or an IO error occurs during copying.

copyFile

public static void copyFile(java.io.File source,
                            java.io.File destination)
                     throws java.io.IOException
Copy file from source to destination. The directories up to destination will be created if they don't already exist. destination will be overwritten if it already exists. The copy will have the same file date as the original.

Parameters:
source - An existing non-directory File to copy bytes from.
destination - A non-directory File to write bytes to (possibly overwriting).
Throws:
java.io.IOException - if source does not exist, destination cannot be written to, or an IO error occurs during copying.
java.io.FileNotFoundException - if destination is a directory (use copyFileToDirectory(java.io.File, java.io.File)).

copyFile

public static void copyFile(java.io.File source,
                            java.io.File destination,
                            boolean preserveFileDate)
                     throws java.io.IOException
Copy file from source to destination. The directories up to destination will be created if they don't already exist. destination will be overwritten if it already exists.

Parameters:
source - An existing non-directory File to copy bytes from.
destination - A non-directory File to write bytes to (possibly overwriting).
preserveFileDate - True if the file date of the copy should be the same as the original.
Throws:
java.io.IOException - if source does not exist, destination cannot be written to, or an IO error occurs during copying.
java.io.FileNotFoundException - if destination is a directory (use copyFileToDirectory(java.io.File, java.io.File)).

copyURLToFile

public static void copyURLToFile(java.net.URL source,
                                 java.io.File destination)
                          throws java.io.IOException
Copies bytes from the URL source to a file destination. The directories up to destination will be created if they don't already exist. destination will be overwritten if it already exists.

Parameters:
source - A URL to copy bytes from.
destination - A non-directory File to write bytes to (possibly overwriting).
Throws:
java.io.IOException - if
  • source URL cannot be opened
  • destination cannot be written to
  • an IO error occurs during copying

deleteDirectory

public static void deleteDirectory(java.io.File directory)
                            throws java.io.IOException
Recursively delete a directory.

Parameters:
directory - directory to delete
Throws:
java.io.IOException - in case deletion is unsuccessful

cleanDirectory

public static void cleanDirectory(java.io.File directory)
                           throws java.io.IOException
Clean a directory without deleting it.

Parameters:
directory - directory to clean
Throws:
java.io.IOException - in case cleaning is unsuccessful

waitFor

public static boolean waitFor(java.io.File file,
                              int seconds)
Waits for NFS to propagate a file creation, imposing a timeout.

Parameters:
file - The file
seconds - The maximum time in seconds to wait.
Returns:
True if file exists.

readFileToString

public static java.lang.String readFileToString(java.io.File file,
                                                java.lang.String encoding)
                                         throws java.io.IOException

Reads the contents of a file into a String.

There is no readFileToString method without encoding parameter because the default encoding can differ between platforms and therefore results in inconsistent results.

Parameters:
file - the file to read
encoding - the encoding to use
Returns:
The file contents or null if read failed.
Throws:
java.io.IOException - in case of an I/O error
UnsupportedEncodingException - if the encoding is not supported by the VM

readFileToByteArray

public static byte[] readFileToByteArray(java.io.File file)
                                  throws java.io.IOException

Reads the contents of a file into a byte array.

Parameters:
file - the file to read
Returns:
The file contents or null if read failed.
Throws:
java.io.IOException - in case of an I/O error

writeStringToFile

public static void writeStringToFile(java.io.File file,
                                     java.lang.String data,
                                     java.lang.String encoding)
                              throws java.io.IOException

Writes a String to a file creating the file if it does not exist.

There is no writeStringToFile method without encoding parameter because the default encoding can differ between platforms and therefore results in inconsistent results.

Parameters:
file - the file to write.
data - The content to write to the file.
encoding - encoding to use
Throws:
java.io.IOException - in case of an I/O error
UnsupportedEncodingException - if the encoding is not supported by the VM

writeByteArrayToFile

public static void writeByteArrayToFile(java.io.File file,
                                        byte[] data)
                                 throws java.io.IOException

Writes a byte array to a file creating the file if it does not exist.

Parameters:
file - the file to write to
data - the content to write to the file
Throws:
java.io.IOException - in case of an I/O error

forceDelete

public static void forceDelete(java.io.File file)
                        throws java.io.IOException

Delete a file. If file is a directory, delete it and all sub-directories.

The difference between File.delete() and this method are:

Parameters:
file - file or directory to delete.
Throws:
java.io.IOException - in case deletion is unsuccessful

forceDeleteOnExit

public static void forceDeleteOnExit(java.io.File file)
                              throws java.io.IOException
Schedule a file to be deleted when JVM exits. If file is directory delete it and all sub-directories.

Parameters:
file - file or directory to delete.
Throws:
java.io.IOException - in case deletion is unsuccessful

deleteDirectoryOnExit

private static void deleteDirectoryOnExit(java.io.File directory)
                                   throws java.io.IOException
Recursively schedule directory for deletion on JVM exit.

Parameters:
directory - directory to delete.
Throws:
java.io.IOException - in case deletion is unsuccessful

cleanDirectoryOnExit

private static void cleanDirectoryOnExit(java.io.File directory)
                                  throws java.io.IOException
Clean a directory without deleting it.

Parameters:
directory - directory to clean.
Throws:
java.io.IOException - in case cleaning is unsuccessful

forceMkdir

public static void forceMkdir(java.io.File directory)
                       throws java.io.IOException
Make a directory. If there already exists a file with specified name or the directory cannot be created then an exception is thrown.

Parameters:
directory - directory to create
Throws:
java.io.IOException - if the directory cannot be created.

sizeOfDirectory

public static long sizeOfDirectory(java.io.File directory)
Recursively count size of a directory (sum of the length of all files).

Parameters:
directory - directory to inspect
Returns:
size of directory in bytes.

isFileNewer

public static boolean isFileNewer(java.io.File file,
                                  java.io.File reference)
Tests if the specified File is newer than the reference File.

Parameters:
file - the File of which the modification date must be compared.
reference - the File of which the modification date is used. like reference
Returns:
true if the File exists and has been modified more recently than the reference File.

isFileNewer

public static boolean isFileNewer(java.io.File file,
                                  java.util.Date date)
Tests if the specified File is newer than the specified Date.

Parameters:
file - the File of which the modification date must be compared.
date - the date reference
Returns:
true if the File exists and has been modified after the given Date.

isFileNewer

public static boolean isFileNewer(java.io.File file,
                                  long timeMillis)
Tests if the specified File is newer than the specified time reference.

Parameters:
file - the File of which the modification date must be compared.
timeMillis - the time reference measured in milliseconds since the epoch (00:00:00 GMT, January 1, 1970)
Returns:
true if the File exists and has been modified after the given time reference.