org.codehaus.plexus.util

Class FileUtils

public class FileUtils extends 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 {@link #catPath concatenate two paths}, {@link #resolveFile resolve a path relative to a File} and {@link #normalize} a path.

File-related methods

There are methods to create a {@link #toFile File from a URL}, copy a {@link #copyFileToDirectory File to a directory}, copy a {@link #copyFile File to another File}, copy a {@link #copyURLToFile URL's contents to a File}, as well as methods to {@link #deleteDirectory(File) delete} and {@link #cleanDirectory(File) clean} a directory.

Common {@link java.io.File} manipulation routines. Taken from the commons-utils repo. Also code from Alexandria's FileUtils. And from Avalon Excalibur's IO. And from Ant.

Version: $Id: FileUtils.java 3082 2006-03-22 07:45:23Z jtolentino $

Author: Kevin A. Burton Scott Sanders Daniel Rall Christoph.Reck Peter Donald Jeff Turner

Nested Class Summary
abstract static classFileUtils.FilterWrapper
Field Summary
static StringFS
static intONE_GB
The number of bytes in a gigabyte.
static intONE_KB
The number of bytes in a kilobyte.
static intONE_MB
The number of bytes in a megabyte.
Method Summary
static Stringbasename(String filename)
Returns the filename portion of a file specification string.
static Stringbasename(String filename, String suffix)
Returns the filename portion of a file specification string.
static VectorblendFilesToVector(Vector v, String[] files)
Private hepler method for getFilesFromExtension()
static StringbyteCountToDisplaySize(int size)
Returns a human-readable version of the file size (original is in bytes).
static StringcatPath(String lookupPath, String path)
Will concatenate 2 paths.
static voidcleanDirectory(String directory)
Clean a directory without deleting it.
static voidcleanDirectory(File directory)
Clean a directory without deleting it.
static voidcleanDirectoryOnExit(File directory)
Clean a directory without deleting it.
static booleancontentEquals(File file1, File file2)
Compare the contents of two files to determine if they are equal or not.
static voidcopyDirectory(File sourceDirectory, File destinationDirectory)
static voidcopyDirectory(File sourceDirectory, File destinationDirectory, String includes, String excludes)
static voidcopyDirectoryStructure(File sourceDirectory, File destinationDirectory)
Copies a entire directory structure.
static voidcopyDirectoryStructureIfModified(File sourceDirectory, File destinationDirectory)
Copies an entire directory structure but only source files with timestamp later than the destinations'.
static voidcopyFile(File source, File destination)
Copy file from source to destination.
static voidcopyFile(File from, File to, String encoding, FileUtils.FilterWrapper[] wrappers)
static voidcopyFileIfModified(File source, File destination)
Copy file from source to destination only if source timestamp is later than the destination timestamp.
static voidcopyFileToDirectory(String source, String destinationDirectory)
Copy file from source to destination.
static voidcopyFileToDirectory(File source, File destinationDirectory)
Copy file from source to destination.
static voidcopyFileToDirectoryIfModified(String source, String destinationDirectory)
Copy file from source to destination only if source is newer than the target file.
static voidcopyFileToDirectoryIfModified(File source, File destinationDirectory)
Copy file from source to destination only if source is newer than the target file.
static voidcopyURLToFile(URL source, File destination)
Copies bytes from the URL source to a file destination.
static FilecreateTempFile(String prefix, String suffix, File parentDir)
Create a temporary file in a given directory.
static voiddeleteDirectory(String directory)
Recursively delete a directory.
static voiddeleteDirectory(File directory)
Recursively delete a directory.
static voiddeleteDirectoryOnExit(File directory)
Recursively schedule directory for deletion on JVM exit.
static booleandeleteFile(File file)
Accommodate Windows bug encountered in both Sun and IBM JDKs.
static Stringdirname(String filename)
Returns the directory path portion of a file specification string.
static Stringextension(String filename)
Returns the extension portion of a file specification string.
static voidfileAppend(String fileName, String data)
Appends data to a file.
static voidfileDelete(String fileName)
Deletes a file.
static booleanfileExists(String fileName)
Check if a file exits.
static Stringfilename(String filename)
Returns the filename portion of a file specification string.
static StringfileRead(String file)
static StringfileRead(File file)
static voidfileWrite(String fileName, String data)
Writes data to a file.
static voidforceDelete(String file)
Delete a file.
static voidforceDelete(File file)
Delete a file.
static voidforceDeleteOnExit(File file)
Schedule a file to be deleted when JVM exits.
static voidforceMkdir(File file)
Make a directory.
static String[]getDefaultExcludes()
static ListgetDefaultExcludesAsList()
static StringgetExtension(String filename)
Get extension from filename. ie
 foo.txt    --> "txt"
 a\b\c.jpg --> "jpg"
 a\b\c     --> ""
 
static FilegetFile(String fileName)
Creates a file handle.
static ListgetFileNames(File directory, String includes, String excludes, boolean includeBasedir)
Return a list of files as String depending options.
static ListgetFileNames(File directory, String includes, String excludes, boolean includeBasedir, boolean isCaseSensitive)
Return a list of files as String depending options.
static ListgetFiles(File directory, String includes, String excludes)
static ListgetFiles(File directory, String includes, String excludes, boolean includeBasedir)
static String[]getFilesFromExtension(String directory, String[] extensions)
Given a directory and an array of extensions return an array of compliant files.
static StringgetPath(String filepath)
Get path from filename.
static StringgetPath(String filepath, char fileSeparatorChar)
Get path from filename. ie.
static booleanisValidFile(String file, String[] extensions)
Checks to see if a file is of a particular type(s).
static voidmkdir(String dir)
Simple way to make a directory
static Stringnormalize(String path)
Normalize a path.
static StringremoveExtension(String filename)
Remove extension from filename. ie
 foo.txt    --> foo
 a\b\c.jpg --> a\b\c
 a\b\c     --> a\b\c
 
static StringremovePath(String filepath)
Remove path from filename.
static StringremovePath(String filepath, char fileSeparatorChar)
Remove path from filename. ie.
static voidrename(File from, File to)
Renames a file, even if that involves crossing file system boundaries.
static FileresolveFile(File baseFile, String filename)
Resolve a file filename to it's canonical form.
static longsizeOfDirectory(String directory)
Recursively count size of a directory.
static longsizeOfDirectory(File directory)
Recursively count size of a directory.
static FiletoFile(URL url)
Convert from a URL to a File.
static URL[]toURLs(File[] files)
Convert the array of Files into a list of URLs.
static booleanwaitFor(String fileName, int seconds)
Waits for NFS to propagate a file creation, imposing a timeout.
static booleanwaitFor(File file, int seconds)

Field Detail

FS

public static String FS

ONE_GB

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

ONE_KB

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

ONE_MB

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

Method Detail

basename

public static String basename(String filename)
Returns the filename portion of a file specification string. Matches the equally named unix command.

Returns: The filename string without extension.

basename

public static String basename(String filename, String suffix)
Returns the filename portion of a file specification string. Matches the equally named unix command.

blendFilesToVector

private static Vector blendFilesToVector(Vector v, String[] files)
Private hepler method for getFilesFromExtension()

byteCountToDisplaySize

public static String byteCountToDisplaySize(int 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).

catPath

public static String catPath(String lookupPath, String path)
Will concatenate 2 paths. Paths with .. will be properly handled.

Eg.,
/a/b/c + d = /a/b/d
/a/b/c + ../d = /a/d

Thieved from Tomcat sources...

Returns: The concatenated paths, or null if error occurs

cleanDirectory

public static void cleanDirectory(String directory)
Clean a directory without deleting it.

cleanDirectory

public static void cleanDirectory(File directory)
Clean a directory without deleting it.

cleanDirectoryOnExit

private static void cleanDirectoryOnExit(File directory)
Clean a directory without deleting it.

contentEquals

public static boolean contentEquals(File file1, File file2)
Compare the contents of two files to determine if they are equal or not.

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

copyDirectory

public static void copyDirectory(File sourceDirectory, File destinationDirectory)

copyDirectory

public static void copyDirectory(File sourceDirectory, File destinationDirectory, String includes, String excludes)

copyDirectoryStructure

public static void copyDirectoryStructure(File sourceDirectory, File destinationDirectory)
Copies a entire directory structure. Note:

Parameters: sourceDirectory destinationDirectory

Throws: IOException

copyDirectoryStructureIfModified

public static void copyDirectoryStructureIfModified(File sourceDirectory, File destinationDirectory)
Copies an entire directory structure but only source files with timestamp later than the destinations'. Note:

Parameters: sourceDirectory destinationDirectory

Throws: IOException

copyFile

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

Throws: 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 {@link #copyFileToDirectory}).

copyFile

public static void copyFile(File from, File to, String encoding, FileUtils.FilterWrapper[] wrappers)

copyFileIfModified

public static void copyFileIfModified(File source, File destination)
Copy file from source to destination only if source timestamp is later than the destination timestamp. 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).

Throws: 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 {@link #copyFileToDirectory}).

copyFileToDirectory

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

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. IllegalArgumentException if destinationDirectory isn't a directory. IOException if source does not exist, the file in destinationDirectory cannot be written to, or an IO error occurs during copying.

copyFileToDirectory

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

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. IllegalArgumentException if destinationDirectory isn't a directory. IOException if source does not exist, the file in destinationDirectory cannot be written to, or an IO error occurs during copying.

copyFileToDirectoryIfModified

public static void copyFileToDirectoryIfModified(String source, String destinationDirectory)
Copy file from source to destination only if source is newer than the target file. If destinationDirectory does not exist, it (and any parent directories) will be created. If a file source in destinationDirectory exists, it will be overwritten.

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. IllegalArgumentException if destinationDirectory isn't a directory. IOException if source does not exist, the file in destinationDirectory cannot be written to, or an IO error occurs during copying.

copyFileToDirectoryIfModified

public static void copyFileToDirectoryIfModified(File source, File destinationDirectory)
Copy file from source to destination only if source is newer than the target file. If destinationDirectory does not exist, it (and any parent directories) will be created. If a file source in destinationDirectory exists, it will be overwritten.

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. IllegalArgumentException if destinationDirectory isn't a directory. IOException if source does not exist, the file in destinationDirectory cannot be written to, or an IO error occurs during copying.

copyURLToFile

public static void copyURLToFile(URL source, File destination)
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: IOException if

createTempFile

public static File createTempFile(String prefix, String suffix, File parentDir)
Create a temporary file in a given directory.

The file denoted by the returned abstract pathname did not exist before this method was invoked, any subsequent invocation of this method will yield a different file name.

The filename is prefixNNNNNsuffix where NNNN is a random number

This method is different to File.createTempFile of JDK 1.2 as it doesn't create the file itself. It uses the location pointed to by java.io.tmpdir when the parentDir attribute is null.

Parameters: prefix prefix before the random number suffix file extension; include the '.' parentDir Directory to create the temporary file in - java.io.tmpdir used if not specificed

Returns: a File reference to the new temporary file.

deleteDirectory

public static void deleteDirectory(String directory)
Recursively delete a directory.

deleteDirectory

public static void deleteDirectory(File directory)
Recursively delete a directory.

deleteDirectoryOnExit

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

deleteFile

private static boolean deleteFile(File file)
Accommodate Windows bug encountered in both Sun and IBM JDKs. Others possible. If the delete does not work, call System.gc(), wait a little and try again.

dirname

public static String dirname(String filename)
Returns the directory path portion of a file specification string. Matches the equally named unix command.

Returns: The directory portion excluding the ending file separator.

extension

public static String extension(String filename)
Returns the extension portion of a file specification string. This everything after the last dot '.' in the filename (NOT including the dot).

fileAppend

public static void fileAppend(String fileName, String data)
Appends data to a file. The file will be created if it does not exist.

Parameters: fileName The name of the file to write. data The content to write to the file.

fileDelete

public static void fileDelete(String fileName)
Deletes a file.

Parameters: fileName The name of the file to delete.

fileExists

public static boolean fileExists(String fileName)
Check if a file exits.

Parameters: fileName The name of the file to check.

Returns: true if file exists.

filename

public static String filename(String filename)
Returns the filename portion of a file specification string.

Returns: The filename string with extension.

fileRead

public static String fileRead(String file)

fileRead

public static String fileRead(File file)

fileWrite

public static void fileWrite(String fileName, String data)
Writes data to a file. The file will be created if it does not exist.

Parameters: fileName The name of the file to write. data The content to write to the file.

forceDelete

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

forceDelete

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

forceDeleteOnExit

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

forceMkdir

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

getDefaultExcludes

public static String[] getDefaultExcludes()

getDefaultExcludesAsList

public static List getDefaultExcludesAsList()

getExtension

public static String getExtension(String filename)
Get extension from filename. ie
 foo.txt    --> "txt"
 a\b\c.jpg --> "jpg"
 a\b\c     --> ""
 

Parameters: filename the filename

Returns: the extension of filename or "" if none

getFile

public static File getFile(String fileName)
Creates a file handle.

Parameters: fileName The name of the file.

Returns: A File manager.

getFileNames

public static List getFileNames(File directory, String includes, String excludes, boolean includeBasedir)
Return a list of files as String depending options. This method use case sensitive file name.

Parameters: directory the directory to scan includes the includes pattern, comma separated excludes the excludes pattern, comma separated includeBasedir true to include the base dir in each String of file

Returns: a list of files as String

Throws: IOException

getFileNames

public static List getFileNames(File directory, String includes, String excludes, boolean includeBasedir, boolean isCaseSensitive)
Return a list of files as String depending options.

Parameters: directory the directory to scan includes the includes pattern, comma separated excludes the excludes pattern, comma separated includeBasedir true to include the base dir in each String of file isCaseSensitive true if case sensitive

Returns: a list of files as String

Throws: IOException

getFiles

public static List getFiles(File directory, String includes, String excludes)

getFiles

public static List getFiles(File directory, String includes, String excludes, boolean includeBasedir)

getFilesFromExtension

public static String[] getFilesFromExtension(String directory, String[] extensions)
Given a directory and an array of extensions return an array of compliant files. TODO Should an ignore list be passed in? TODO Should a recurse flag be passed in? The given extensions should be like "java" and not like ".java"

getPath

public static String getPath(String filepath)
Get path from filename. Roughly equivalent to the unix command dirname. ie.
 a/b/c.txt --> a/b
 a.txt     --> ""
 

Parameters: filepath the filepath

Returns: the filename minus path

getPath

public static String getPath(String filepath, char fileSeparatorChar)
Get path from filename. ie.
 a/b/c.txt --> a/b
 a.txt     --> ""
 

Parameters: filepath the filepath

Returns: the filename minus path

isValidFile

private static boolean isValidFile(String file, String[] extensions)
Checks to see if a file is of a particular type(s). Note that if the file does not have an extension, an empty string ("") is matched for.

mkdir

public static void mkdir(String dir)
Simple way to make a directory

normalize

public static String normalize(String path)
Normalize a path. Eliminates "/../" and "/./" in a string. Returns null if the ..'s went past the root. Eg:
 /foo//               -->     /foo/
 /foo/./              -->     /foo/
 /foo/../bar          -->     /bar
 /foo/../bar/         -->     /bar/
 /foo/../bar/../baz   -->     /baz
 //foo//./bar         -->     /foo/bar
 /../                 -->     null
 

Parameters: path the path to normalize

Returns: the normalized String, or null if too many ..'s.

removeExtension

public static String removeExtension(String filename)
Remove extension from filename. ie
 foo.txt    --> foo
 a\b\c.jpg --> a\b\c
 a\b\c     --> a\b\c
 

Parameters: filename the filename

Returns: the filename minus extension

removePath

public static String removePath(String filepath)
Remove path from filename. Equivalent to the unix command basename ie.
 a/b/c.txt --> c.txt
 a.txt     --> a.txt
 

Parameters: filepath the filepath

Returns: the filename minus path

removePath

public static String removePath(String filepath, char fileSeparatorChar)
Remove path from filename. ie.
 a/b/c.txt --> c.txt
 a.txt     --> a.txt
 

Parameters: filepath the filepath

Returns: the filename minus path

rename

public static void rename(File from, File to)
Renames a file, even if that involves crossing file system boundaries.

This will remove to (if it exists), ensure that to's parent directory exists and move from, which involves deleting from as well.

Parameters: from the file to move to the new file name

Throws: IOException if anything bad happens during this process. Note that to may have been deleted already when this happens.

resolveFile

public static File resolveFile(File baseFile, String filename)
Resolve a file filename to it's canonical form. If filename is relative (doesn't start with /), it will be resolved relative to baseFile, otherwise it is treated as a normal root-relative path.

Parameters: baseFile Where to resolve filename from, if filename is relative. filename Absolute or relative file path to resolve.

Returns: The canonical File of filename.

sizeOfDirectory

public static long sizeOfDirectory(String directory)
Recursively count size of a directory.

Returns: size of directory in bytes.

sizeOfDirectory

public static long sizeOfDirectory(File directory)
Recursively count size of a directory.

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

toURLs

public static URL[] toURLs(File[] files)
Convert the array of Files into a list of URLs.

Parameters: files the array of files

Returns: the array of URLs

Throws: IOException if an error occurs

waitFor

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

Parameters: fileName The name of the file. seconds The maximum time in seconds to wait.

Returns: True if file exists.

waitFor

public static boolean waitFor(File file, int seconds)