org.apache.maven.shared.utils.io
Class FileUtils

java.lang.Object
  extended by org.apache.maven.shared.utils.io.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:

File-related methods

There are methods to create a File from a URL, copy a 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.

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 1401850 2012-10-24 19:59:48Z rfscholte $
Author:
Kevin A. Burton, Scott Sanders, Daniel Rall, Christoph.Reck, Peter Donald, Jeff Turner

Nested Class Summary
static class FileUtils.FilterWrapper
           
 
Constructor Summary
protected FileUtils()
           
 
Method Summary
static void cleanDirectory(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 void copyDirectory(File sourceDirectory, File destinationDirectory)
          Copy a directory to an other one.
static void copyDirectory(File sourceDirectory, File destinationDirectory, String includes, String excludes)
          Copy a directory to an other one.
static void copyDirectoryStructure(File sourceDirectory, File destinationDirectory)
          Copies a entire directory structure.
static void copyFile(File source, File destination)
          Copy file from source to destination.
static void copyFile(File from, File to, String encoding, FileUtils.FilterWrapper... wrappers)
          If wrappers is null or empty, the file will be copy only if to.lastModified() < from.lastModified()
static void copyFile(File from, File to, String encoding, FileUtils.FilterWrapper[] wrappers, boolean overwrite)
          If wrappers is null or empty, the file will be copy only if to.lastModified() < from.lastModified() or if overwrite is true
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 File createTempFile(String prefix, String suffix, File parentDir)
          Create a temporary file in a given directory.
static void deleteDirectory(File directory)
          Recursively delete a directory.
static void deleteDirectory(String directory)
          Recursively delete a directory.
static String dirname(String filename)
          Returns the directory path portion of a file specification string.
static String extension(String filename)
          Returns the extension portion of a file specification string.
static void fileAppend(String fileName, String data)
          Appends data to a file.
static void fileAppend(String fileName, String encoding, String data)
          Appends data to a file.
static void fileDelete(String fileName)
          Deletes a file.
static boolean fileExists(String fileName)
          Check if a file exits.
static String filename(String filename)
          Returns the filename portion of a file specification string.
static String fileRead(File file)
          Note: the file content is read with platform encoding
static String fileRead(File file, String encoding)
           
static String fileRead(String file)
          Note: the file content is read with platform encoding.
static String[] fileReadArray(File file)
           
static void fileWrite(File file, String encoding, String data)
          Writes data to a file.
static void fileWrite(String fileName, String data)
          Writes data to a file.
static void fileWrite(String fileName, String encoding, String data)
          Writes data to a file.
static void fileWriteArray(File file, String... data)
          Writes String array data to a file in the systems default encoding.
static void fileWriteArray(File file, String encoding, String... data)
          Writes String array data to a file.
static void forceDelete(File file)
          Delete a file.
static void forceDelete(String file)
          Delete a file.
static void forceMkdir(File file)
          Make a directory.
static String[] getDefaultExcludes()
           
static List<String> getDefaultExcludesAsList()
           
static String getDefaultExcludesAsString()
           
static List<String> getDirectoryNames(File directory, String includes, String excludes, boolean includeBasedir)
          Return a list of directories as String depending options.
static List<String> getDirectoryNames(File directory, String includes, String excludes, boolean includeBasedir, boolean isCaseSensitive)
          Return a list of directories as String depending options.
static String getExtension(String filename)
          Get extension from filename.
static List<String> getFileAndDirectoryNames(File directory, String includes, String excludes, boolean includeBasedir, boolean isCaseSensitive, boolean getFiles, boolean getDirectories)
          Return a list of files as String depending options.
static List<String> getFileNames(File directory, String includes, String excludes, boolean includeBasedir)
          Return a list of files as String depending options.
static List<File> getFiles(File directory, String includes, String excludes)
          Return the files contained in the directory, using inclusion and exclusion Ant patterns, including the directory name in each of the files
static List<File> getFiles(File directory, String includes, String excludes, boolean includeBasedir)
          Return the files contained in the directory, using inclusion and exclusion Ant patterns
static String[] getFilesFromExtension(String directory, String... extensions)
          Given a directory and an array of extensions return an array of compliant files.
static List<String> loadFile(File file)
          Note: the file content is read with platform encoding
static void mkdir(String dir)
          Simple way to make a directory
static String normalize(String path)
          Normalize a path.
static String removeExtension(String filename)
          Remove extension from filename.
static void rename(File from, File to)
          Renames a file, even if that involves crossing file system boundaries.
static File resolveFile(File baseFile, String filename)
          Resolve a file filename to it's canonical form.
static long sizeOfDirectory(File directory)
          Recursively count size of a directory.
static long sizeOfDirectory(String directory)
          Recursively count size of a directory.
static File toFile(URL url)
          Convert from a URL to a File.
static URL[] toURLs(File... files)
          Convert the array of Files into a list of URLs.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

FileUtils

protected FileUtils()
Method Detail

getDefaultExcludes

@Nonnull
public static String[] getDefaultExcludes()
Returns:
the default excludes pattern
See Also:
DirectoryScanner.DEFAULTEXCLUDES

getDefaultExcludesAsList

@Nonnull
public static List<String> getDefaultExcludesAsList()
Returns:
the default excludes pattern as list.
See Also:
getDefaultExcludes()

getDefaultExcludesAsString

@Nonnull
public static String getDefaultExcludesAsString()
Returns:
the default excludes pattern as comma separated string.
See Also:
DirectoryScanner.DEFAULTEXCLUDES, StringUtils.join(Object[], String)

dirname

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

Parameters:
filename - the file path
Returns:
The directory portion excluding the ending file separator.

filename

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

Parameters:
filename - the file path
Returns:
The filename string with extension.

extension

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

Parameters:
filename - the file path
Returns:
the extension of the file

fileExists

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

Parameters:
fileName - the file path.
Returns:
true if file exists.

fileRead

@Nonnull
public static String fileRead(@Nonnull
                                      String file)
                       throws IOException
Note: the file content is read with platform encoding.

Parameters:
file - the file path
Returns:
the file content using the platform encoding.
Throws:
IOException - if any

fileRead

@Nonnull
public static String fileRead(@Nonnull
                                      File file)
                       throws IOException
Note: the file content is read with platform encoding

Parameters:
file - the file path
Returns:
the file content using the platform encoding.
Throws:
IOException - if any

fileRead

@Nonnull
public static String fileRead(@Nonnull
                                      File file,
                                      @Nullable
                                      String encoding)
                       throws IOException
Parameters:
file - the file path
encoding - the wanted encoding
Returns:
the file content using the specified encoding.
Throws:
IOException - if any

fileReadArray

@Nonnull
public static String[] fileReadArray(@Nonnull
                                             File file)
                              throws IOException
Parameters:
file - the file path
Returns:
the file content lines as String[] using the systems default encoding. An empty List if the file didn't exist.
Throws:
IOException

fileAppend

public static void fileAppend(@Nonnull
                              String fileName,
                              @Nonnull
                              String data)
                       throws IOException
Appends data to a file. The file will be created if it does not exist. Note: the data is written with platform encoding

Parameters:
fileName - The path of the file to write.
data - The content to write to the file.
Throws:
IOException - if any

fileAppend

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

Parameters:
fileName - The path of the file to write.
encoding - The encoding of the file.
data - The content to write to the file.
Throws:
IOException - if any

fileWrite

public static void fileWrite(@Nonnull
                             String fileName,
                             @Nonnull
                             String data)
                      throws IOException
Writes data to a file. The file will be created if it does not exist. Note: the data is written with platform encoding

Parameters:
fileName - The path of the file to write.
data - The content to write to the file.
Throws:
IOException - if any

fileWrite

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

Parameters:
fileName - The path of the file to write.
encoding - The encoding of the file.
data - The content to write to the file.
Throws:
IOException - if any

fileWrite

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

Parameters:
file - The path of the file to write.
encoding - The encoding of the file.
data - The content to write to the file.
Throws:
IOException - if any

fileWriteArray

public static void fileWriteArray(@Nonnull
                                  File file,
                                  @Nullable
                                  String... data)
                           throws IOException
Writes String array data to a file in the systems default encoding. The file will be created if it does not exist.

Parameters:
file - The path of the file to write.
data - The content to write to the file.
Throws:
IOException - if any

fileWriteArray

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

Parameters:
file - The path of the file to write.
encoding - The encoding of the file.
data - The content to write to the file.
Throws:
IOException - if any

fileDelete

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

Parameters:
fileName - The path of the file to delete.

getFilesFromExtension

public static String[] getFilesFromExtension(@Nonnull
                                             String directory,
                                             @Nonnull
                                             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"

Parameters:
directory - The path of the directory.
extensions - an array of expected extensions.
Returns:
An array of files for the wanted extensions.

mkdir

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

Parameters:
dir - the directory to create
Throws:
IllegalArgumentException - if the dir contains illegal Windows characters under Windows OS.
See Also:
INVALID_CHARACTERS_FOR_WINDOWS_FILE_NAME

contentEquals

public static boolean contentEquals(@Nonnull
                                    File file1,
                                    @Nonnull
                                    File file2)
                             throws IOException
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
Throws:
IOException - if any

toFile

@Nullable
public static File toFile(@Nullable
                                   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

@Nonnull
public static URL[] toURLs(@Nonnull
                                   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
Throws:
IOException - if an error occurs

removeExtension

@Nonnull
public static String removeExtension(@Nonnull
                                             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 path of the file
Returns:
the filename minus extension

getExtension

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

Parameters:
filename - the path of the file
Returns:
the extension of filename or "" if none

copyFileToDirectory

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

Parameters:
source - An existing File to copy.
destinationDirectory - A directory to copy source into.
Throws:
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.

copyFile

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

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.
FileNotFoundException - if destination is a directory

copyURLToFile

public static void copyURLToFile(@Nonnull
                                 URL source,
                                 @Nonnull
                                 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).
Throws:
IOException - if
  • source URL cannot be opened
  • destination cannot be written to
  • an IO error occurs during copying

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.

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.

forceDelete

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

Parameters:
file - the file path
Throws:
IOException - if any

forceDelete

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

Parameters:
file - a file
Throws:
IOException - if any

forceMkdir

public static void forceMkdir(@Nonnull
                              File file)
                       throws IOException
Make a directory.

Parameters:
file - not null
Throws:
IOException - If there already exists a file with specified name or the directory is unable to be created
IllegalArgumentException - if the file contains illegal Windows characters under Windows OS.
See Also:
INVALID_CHARACTERS_FOR_WINDOWS_FILE_NAME

deleteDirectory

public static void deleteDirectory(@Nonnull
                                   String directory)
                            throws IOException
Recursively delete a directory.

Parameters:
directory - a directory
Throws:
IOException - if any

deleteDirectory

public static void deleteDirectory(@Nonnull
                                   File directory)
                            throws IOException
Recursively delete a directory.

Parameters:
directory - a directory
Throws:
IOException - if any

cleanDirectory

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

Parameters:
directory - a directory
Throws:
IOException - if any

sizeOfDirectory

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

Parameters:
directory - a directory
Returns:
size of directory in bytes.

sizeOfDirectory

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

Parameters:
directory - a directory
Returns:
size of directory in bytes.

getFiles

@Nonnull
public static List<File> getFiles(@Nonnull
                                          File directory,
                                          @Nullable
                                          String includes,
                                          @Nullable
                                          String excludes)
                           throws IOException
Return the files contained in the directory, using inclusion and exclusion Ant patterns, including the directory name in each of the files

Parameters:
directory - the directory to scan
includes - the includes pattern, comma separated
excludes - the excludes pattern, comma separated
Returns:
a list of File objects
Throws:
IOException
See Also:
getFileNames(File, String, String, boolean)

getFiles

@Nonnull
public static List<File> getFiles(@Nonnull
                                          File directory,
                                          @Nullable
                                          String includes,
                                          @Nullable
                                          String excludes,
                                          boolean includeBasedir)
                           throws IOException
Return the files contained in the directory, using inclusion and exclusion Ant patterns

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 file
Returns:
a list of File objects
Throws:
IOException
See Also:
getFileNames(File, String, String, boolean)

getFileNames

@Nonnull
public static List<String> getFileNames(@Nonnull
                                                File directory,
                                                @Nullable
                                                String includes,
                                                @Nullable
                                                String excludes,
                                                boolean includeBasedir)
                                 throws IOException
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

getDirectoryNames

@Nonnull
public static List<String> getDirectoryNames(@Nonnull
                                                     File directory,
                                                     @Nullable
                                                     String includes,
                                                     @Nullable
                                                     String excludes,
                                                     boolean includeBasedir)
                                      throws IOException
Return a list of directories 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 directories as String
Throws:
IOException

getDirectoryNames

@Nonnull
public static List<String> getDirectoryNames(@Nonnull
                                                     File directory,
                                                     @Nullable
                                                     String includes,
                                                     @Nullable
                                                     String excludes,
                                                     boolean includeBasedir,
                                                     boolean isCaseSensitive)
                                      throws IOException
Return a list of directories 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 directories as String
Throws:
IOException

getFileAndDirectoryNames

@Nonnull
public static List<String> getFileAndDirectoryNames(File directory,
                                                            @Nullable
                                                            String includes,
                                                            @Nullable
                                                            String excludes,
                                                            boolean includeBasedir,
                                                            boolean isCaseSensitive,
                                                            boolean getFiles,
                                                            boolean getDirectories)
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
getFiles - true if get files
getDirectories - true if get directories
Returns:
a list of files as String

copyDirectory

public static void copyDirectory(File sourceDirectory,
                                 File destinationDirectory)
                          throws IOException
Copy a directory to an other one.

Parameters:
sourceDirectory - the source dir
destinationDirectory - the target dir
Throws:
IOException - if any

copyDirectory

public static void copyDirectory(@Nonnull
                                 File sourceDirectory,
                                 @Nonnull
                                 File destinationDirectory,
                                 @Nullable
                                 String includes,
                                 @Nullable
                                 String excludes)
                          throws IOException
Copy a directory to an other one.

Parameters:
sourceDirectory - the source dir
destinationDirectory - the target dir
includes - include pattern
excludes - exlucde pattern
Throws:
IOException - if any
See Also:
getFiles(File, String, String)

copyDirectoryStructure

public static void copyDirectoryStructure(@Nonnull
                                          File sourceDirectory,
                                          @Nonnull
                                          File destinationDirectory)
                                   throws IOException
Copies a entire directory structure.

Note:

Parameters:
sourceDirectory - the source dir
destinationDirectory - the target dir
Throws:
IOException - if any

rename

public static void rename(@Nonnull
                          File from,
                          @Nonnull
                          File to)
                   throws IOException
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.

createTempFile

public static File createTempFile(@Nonnull
                                  String prefix,
                                  @Nonnull
                                  String suffix,
                                  @Nullable
                                  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(String, String, File) 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.

To delete automatically the file created by this method, use the File.deleteOnExit() method.

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.

copyFile

public static void copyFile(@Nonnull
                            File from,
                            @Nonnull
                            File to,
                            @Nullable
                            String encoding,
                            @Nullable
                            FileUtils.FilterWrapper... wrappers)
                     throws IOException
If wrappers is null or empty, the file will be copy only if to.lastModified() < from.lastModified()

Parameters:
from - the file to copy
to - the destination file
encoding - the file output encoding (only if wrappers is not empty)
wrappers - array of FileUtils.FilterWrapper
Throws:
IOException - if an IO error occurs during copying or filtering

copyFile

public static void copyFile(@Nonnull
                            File from,
                            @Nonnull
                            File to,
                            @Nullable
                            String encoding,
                            @Nullable
                            FileUtils.FilterWrapper[] wrappers,
                            boolean overwrite)
                     throws IOException
If wrappers is null or empty, the file will be copy only if to.lastModified() < from.lastModified() or if overwrite is true

Parameters:
from - the file to copy
to - the destination file
encoding - the file output encoding (only if wrappers is not empty)
wrappers - array of FileUtils.FilterWrapper
overwrite - if true and f wrappers is null or empty, the file will be copy enven if to.lastModified() < from.lastModified()
Throws:
IOException - if an IO error occurs during copying or filtering

loadFile

@Nonnull
public static List<String> loadFile(@Nonnull
                                            File file)
                             throws IOException
Note: the file content is read with platform encoding

Parameters:
file - the file
Returns:
a List containing every every line not starting with # and not empty
Throws:
IOException - if any


Copyright © 2002-2013 The Apache Software Foundation. All Rights Reserved.