org.apache.commons.io

Class FileUtils


public class FileUtils
extends java.lang.Object

This class provides basic facilities for manipulating files and file paths.

Path-related methods

Methods exist to retrieve the components of a typical file path. For example /www/hosted/mysite/index.html, can be broken into:

There are also methods to concatenate two paths, resolve a path relative to a File and FileUtils a path.

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 java.io.File manipulation routines.

Origin of code

Version:
$Id: FileUtils.java,v 1.31 2004/04/24 19:46:16 jeremias Exp $
Authors:
Kevin A. Burton
Scott Sanders
Daniel Rall
Christoph.Reck
Peter Donald
Jeff Turner
Matthew Hawthorne
Jeremias Maerki

Field Summary

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 String
byteCountToDisplaySize(long size)
Returns a human-readable version of the file size (original is in bytes).
static void
cleanDirectory(File directory)
Clean a directory without deleting it.
private static void
cleanDirectoryOnExit(File directory)
Clean a directory without deleting it.
static boolean
contentEquals(File file1, File file2)
Compare the contents of two files to determine if they are equal or not.
static File[]
convertFileCollectionToFileArray(Collection files)
Converts a Collection containing java.io.File instanced into array representation.
static void
copyFile(File source, File destination)
Copy file from source to destination.
static void
copyFile(File source, File destination, boolean preserveFileDate)
Copy file from source to destination.
static void
copyFileToDirectory(File source, File destinationDirectory)
Copy file from source to destination.
static void
copyURLToFile(URL source, File destination)
Copies bytes from the URL source to a file destination.
static void
deleteDirectory(File directory)
Recursively delete a directory.
private static void
deleteDirectoryOnExit(File directory)
Recursively schedule directory for deletion on JVM exit.
static void
forceDelete(File file)
Delete a file.
static void
forceDeleteOnExit(File file)
Schedule a file to be deleted when JVM exits.
static void
forceMkdir(File directory)
Make a directory.
private static void
innerListFiles(Collection files, File directory, IOFileFilter filter)
static boolean
isFileNewer(File file, Date date)
Tests if the specified File is newer than the specified Date
static boolean
isFileNewer(File file, File reference)
Tests if the specified File is newer than the reference File.
static boolean
isFileNewer(File file, long timeMillis)
Tests if the specified File is newer than the specified time reference.
static Collection
listFiles(File directory, String[] extensions, boolean recursive)
Finds files within a given directory (and optionally its subdirectories) which match an array of extensions.
static Collection
listFiles(File directory, IOFileFilter fileFilter, IOFileFilter dirFilter)
Finds files within a given directory (and optionally its subdirectories).
static String
readFileToString(File file, String encoding)
Reads the contents of a file into a String.
static long
sizeOfDirectory(File directory)
Recursively count size of a directory (sum of the length of all files).
static File
toFile(URL url)
Convert from a URL to a File.
private static String[]
toSuffixes(String[] extensions)
Converts an array of file extensions to suffixes for use with IOFileFilters.
static URL[]
toURLs(File[] files)
Convert the array of Files into a list of URLs.
static void
touch(File file)
Implements the same behaviour as the "touch" utility on Unix.
static boolean
waitFor(File file, int seconds)
Waits for NFS to propagate a file creation, imposing a timeout.
static void
writeStringToFile(File file, String data, String encoding)
Writes data to a file.

Field Details

ONE_GB

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

ONE_KB

public static final long ONE_KB
The number of bytes in a kilobyte.
Field Value:
1024L

ONE_MB

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

Constructor Details

FileUtils

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

Method Details

byteCountToDisplaySize

public static 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).

cleanDirectory

public static void cleanDirectory(File directory)
            throws IOException
Clean a directory without deleting it.
Parameters:
directory - directory to clean

cleanDirectoryOnExit

private static void cleanDirectoryOnExit(File directory)
            throws IOException
Clean a directory without deleting it.
Parameters:
directory - directory to clean.

contentEquals

public static boolean contentEquals(File file1,
                                    File file2)
            throws 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

convertFileCollectionToFileArray

public static File[] convertFileCollectionToFileArray(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

copyFile

public static void copyFile(File source,
                            File destination)
            throws 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).

copyFile

public static void copyFile(File source,
                            File destination,
                            boolean preserveFileDate)
            throws 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.

copyFileToDirectory

public static void copyFileToDirectory(File source,
                                       File destinationDirectory)
            throws 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.

copyURLToFile

public static void copyURLToFile(URL source,
                                 File destination)
            throws 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).

deleteDirectory

public static void deleteDirectory(File directory)
            throws IOException
Recursively delete a directory.
Parameters:
directory - directory to delete

deleteDirectoryOnExit

private static void deleteDirectoryOnExit(File directory)
            throws IOException
Recursively schedule directory for deletion on JVM exit.
Parameters:
directory - directory to delete.

forceDelete

public static void forceDelete(File file)
            throws IOException
Delete a file. If file is a directory, delete it and all sub-directories.

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

  • A directory to be deleted does not have to be empty.
  • You get exceptions when a file or directory cannot be deleted. (java.io.File methods returns a boolean)
Parameters:
file - file or directory to delete.

forceDeleteOnExit

public static void forceDeleteOnExit(File file)
            throws 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.

forceMkdir

public static void forceMkdir(File directory)
            throws 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

innerListFiles

private static void innerListFiles(Collection files,
                                   File directory,
                                   IOFileFilter filter)

isFileNewer

public static boolean isFileNewer(File file,
                                  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(File file,
                                  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(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.

listFiles

public static Collection listFiles(File directory,
                                   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

listFiles

public static Collection listFiles(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

readFileToString

public static String readFileToString(File file,
                                      String encoding)
            throws 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.

sizeOfDirectory

public static long sizeOfDirectory(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.

toFile

public static File toFile(URL url)
Convert from a URL to a File.
Parameters:
url - File URL.
Returns:
The equivalent File object, or null if the URL's protocol is not file

toSuffixes

private static String[] toSuffixes(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"}

toURLs

public static URL[] toURLs(File[] files)
            throws IOException
Convert the array of Files into a list of URLs.
Parameters:
files - the array of files
Returns:
the array of URLs

touch

public static void touch(File file)
            throws 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

waitFor

public static boolean waitFor(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. TODO Needs a clearer javadoc to see its real purpose for someone without NFS-knowledge.

writeStringToFile

public static void writeStringToFile(File file,
                                     String data,
                                     String encoding)
            throws IOException
Writes data to a file. The file will be created if it does not exist.

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 write.
data - The content to write to the file.
encoding - encoding to use