Class FileUtils
- java.lang.Object
-
- org.gcube.dataanalysis.executor.rscripts.generic.FileUtils
-
public class FileUtils extends Object
General file manipulation utilities.Facilities are provided in the following areas:
- writing to a file
- reading from a file
- make a directory including parent directories
- copying files and directories
- deleting files and directories
- converting to and from a URL
- listing files and directories by filter and extension
- comparing file content
- file last changed date
- calculating a checksum
Origin of code: Excalibur, Alexandria, Commons-Utils
- Version:
- $Id: FileUtils.java 1349509 2012-06-12 20:39:23Z ggregory $
-
-
Field Summary
Fields Modifier and Type Field Description static File[]EMPTY_FILE_ARRAYAn empty array of typeFile.static longONE_EBThe number of bytes in an exabyte.static BigIntegerONE_EB_BIThe number of bytes in an exabyte.static longONE_GBThe number of bytes in a gigabyte.static BigIntegerONE_GB_BIThe number of bytes in a gigabyte.static longONE_KBThe number of bytes in a kilobyte.static BigIntegerONE_KB_BIThe number of bytes in a kilobyte.static longONE_MBThe number of bytes in a megabyte.static BigIntegerONE_MB_BIThe number of bytes in a megabyte.static longONE_PBThe number of bytes in a petabyte.static BigIntegerONE_PB_BIThe number of bytes in a petabyte.static longONE_TBThe number of bytes in a terabyte.static BigIntegerONE_TB_BIThe number of bytes in a terabyte.static BigIntegerONE_YBThe number of bytes in a yottabyte.static BigIntegerONE_ZBThe number of bytes in a zettabyte.
-
Constructor Summary
Constructors Constructor Description FileUtils()Instances should NOT be constructed in standard programming.
-
Method Summary
All Methods Static Methods Concrete Methods Modifier and Type Method Description static StringbyteCountToDisplaySize(long size)Returns a human-readable version of the file size, where the input represents a specific number of bytes.static StringbyteCountToDisplaySize(BigInteger size)Returns a human-readable version of the file size, where the input represents a specific number of bytes.static Checksumchecksum(File file, Checksum checksum)Computes the checksum of a file using the specified checksum object.static longchecksumCRC32(File file)Computes the checksum of a file using the CRC32 checksum routine.static voidcleanDirectory(File directory)Cleans a directory without deleting it.static booleancontentEquals(File file1, File file2)Compares the contents of two files to determine if they are equal or not.static booleancontentEqualsIgnoreEOL(File file1, File file2, String charsetName)Compares the contents of two files to determine if they are equal or not.static File[]convertFileCollectionToFileArray(Collection<File> files)Converts a Collection containing java.io.File instanced into array representation.static voidcopyDirectory(File srcDir, File destDir)Copies a whole directory to a new location preserving the file dates.static voidcopyDirectory(File srcDir, File destDir, boolean preserveFileDate)Copies a whole directory to a new location.static voidcopyDirectory(File srcDir, File destDir, FileFilter filter)Copies a filtered directory to a new location preserving the file dates.static voidcopyDirectory(File srcDir, File destDir, FileFilter filter, boolean preserveFileDate)Copies a filtered directory to a new location.static voidcopyDirectoryToDirectory(File srcDir, File destDir)Copies a directory to within another directory preserving the file dates.static voidcopyFile(File srcFile, File destFile)Copies a file to a new location preserving the file date.static voidcopyFile(File srcFile, File destFile, boolean preserveFileDate)Copies a file to a new location.static longcopyFile(File input, OutputStream output)Copy bytes from aFileto anOutputStream.static voidcopyFileToDirectory(File srcFile, File destDir)Copies a file to a directory preserving the file date.static voidcopyFileToDirectory(File srcFile, File destDir, boolean preserveFileDate)Copies a file to a directory optionally preserving the file date.static voidcopyInputStreamToFile(InputStream source, File destination)static voidcopyURLToFile(URL source, File destination)Copies bytes from the URLsourceto a filedestination.static voidcopyURLToFile(URL source, File destination, int connectionTimeout, int readTimeout)Copies bytes from the URLsourceto a filedestination.static voiddeleteDirectory(File directory)Deletes a directory recursively.static booleandeleteQuietly(File file)Deletes a file, never throwing an exception.static booleandirectoryContains(File directory, File child)Determines whether theparentdirectory contains thechildelement (a file or directory).static voidforceDelete(File file)Deletes a file.static voidforceDeleteOnExit(File file)Schedules a file to be deleted when JVM exits.static voidforceMkdir(File directory)Makes a directory, including any necessary but nonexistent parent directories.static FilegetFile(File directory, String... names)Construct a file from the set of name elements.static FilegetFile(String... names)Construct a file from the set of name elements.static FilegetTempDirectory()Returns aFilerepresenting the system temporary directory.static StringgetTempDirectoryPath()Returns the path to the system temporary directory.static FilegetUserDirectory()Returns aFilerepresenting the user's home directory.static StringgetUserDirectoryPath()Returns the path to the user's home directory.static booleanisFileNewer(File file, long timeMillis)Tests if the specifiedFileis newer than the specified time reference.static booleanisFileNewer(File file, File reference)Tests if the specifiedFileis newer than the referenceFile.static booleanisFileNewer(File file, Date date)Tests if the specifiedFileis newer than the specifiedDate.static booleanisFileOlder(File file, long timeMillis)Tests if the specifiedFileis older than the specified time reference.static booleanisFileOlder(File file, File reference)Tests if the specifiedFileis older than the referenceFile.static booleanisFileOlder(File file, Date date)Tests if the specifiedFileis older than the specifiedDate.static booleanisSymlink(File file)Determines whether the specified file is a Symbolic Link rather than an actual file.static Iterator<File>iterateFiles(File directory, String[] extensions, boolean recursive)Allows iteration over the files in a given directory (and optionally its subdirectories) which match an array of extensions.static Iterator<File>iterateFiles(File directory, org.apache.commons.io.filefilter.IOFileFilter fileFilter, org.apache.commons.io.filefilter.IOFileFilter dirFilter)Allows iteration over the files in given directory (and optionally its subdirectories).static Iterator<File>iterateFilesAndDirs(File directory, org.apache.commons.io.filefilter.IOFileFilter fileFilter, org.apache.commons.io.filefilter.IOFileFilter dirFilter)Allows iteration over the files in given directory (and optionally its subdirectories).static org.apache.commons.io.LineIteratorlineIterator(File file)Returns an Iterator for the lines in aFileusing the default encoding for the VM.static org.apache.commons.io.LineIteratorlineIterator(File file, String encoding)Returns an Iterator for the lines in aFile.static Collection<File>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<File>listFiles(File directory, org.apache.commons.io.filefilter.IOFileFilter fileFilter, org.apache.commons.io.filefilter.IOFileFilter dirFilter)Finds files within a given directory (and optionally its subdirectories).static Collection<File>listFilesAndDirs(File directory, org.apache.commons.io.filefilter.IOFileFilter fileFilter, org.apache.commons.io.filefilter.IOFileFilter dirFilter)Finds files within a given directory (and optionally its subdirectories).static voidmoveDirectory(File srcDir, File destDir)Moves a directory.static voidmoveDirectoryToDirectory(File src, File destDir, boolean createDestDir)Moves a directory to another directory.static voidmoveFile(File srcFile, File destFile)Moves a file.static voidmoveFileToDirectory(File srcFile, File destDir, boolean createDestDir)Moves a file to a directory.static voidmoveFileToDirectory(File srcFile, File destDir, File dstFile, boolean createDestDir)static voidmoveToDirectory(File src, File destDir, boolean createDestDir)Moves a file or directory to the destination directory.static FileInputStreamopenInputStream(File file)Opens aFileInputStreamfor the specified file, providing better error messages than simply callingnew FileInputStream(file).static FileOutputStreamopenOutputStream(File file)Opens aFileOutputStreamfor the specified file, checking and creating the parent directory if it does not exist.static FileOutputStreamopenOutputStream(File file, boolean append)Opens aFileOutputStreamfor the specified file, checking and creating the parent directory if it does not exist.static byte[]readFileToByteArray(File file)Reads the contents of a file into a byte array.static StringreadFileToString(File file)Reads the contents of a file into a String using the default encoding for the VM.static StringreadFileToString(File file, String encoding)Reads the contents of a file into a String.static StringreadFileToString(File file, Charset encoding)Reads the contents of a file into a String.static List<String>readLines(File file)Reads the contents of a file line by line to a List of Strings using the default encoding for the VM.static List<String>readLines(File file, String encoding)Reads the contents of a file line by line to a List of Strings.static List<String>readLines(File file, Charset encoding)Reads the contents of a file line by line to a List of Strings.static longsizeOf(File file)Returns the size of the specified file or directory.static BigIntegersizeOfAsBigInteger(File file)Returns the size of the specified file or directory.static longsizeOfDirectory(File directory)Counts the size of a directory recursively (sum of the length of all files).static BigIntegersizeOfDirectoryAsBigInteger(File directory)Counts the size of a directory recursively (sum of the length of all files).static FiletoFile(URL url)Convert from aURLto aFile.static File[]toFiles(URL[] urls)Converts each of an array ofURLto aFile.static voidtouch(File file)Implements the same behaviour as the "touch" utility on Unix.static URL[]toURLs(File[] files)Converts each of an array ofFileto aURL.static booleanwaitFor(File file, int seconds)Waits for NFS to propagate a file creation, imposing a timeout.static voidwrite(File file, CharSequence data)Writes a CharSequence to a file creating the file if it does not exist using the default encoding for the VM.static voidwrite(File file, CharSequence data, boolean append)Writes a CharSequence to a file creating the file if it does not exist using the default encoding for the VM.static voidwrite(File file, CharSequence data, String encoding)Writes a CharSequence to a file creating the file if it does not exist.static voidwrite(File file, CharSequence data, String encoding, boolean append)Writes a CharSequence to a file creating the file if it does not exist.static voidwrite(File file, CharSequence data, Charset encoding)Writes a CharSequence to a file creating the file if it does not exist.static voidwrite(File file, CharSequence data, Charset encoding, boolean append)Writes a CharSequence to a file creating the file if it does not exist.static voidwriteByteArrayToFile(File file, byte[] data)Writes a byte array to a file creating the file if it does not exist.static voidwriteByteArrayToFile(File file, byte[] data, boolean append)Writes a byte array to a file creating the file if it does not exist.static voidwriteLines(File file, String encoding, Collection<?> lines)Writes thetoString()value of each item in a collection to the specifiedFileline by line.static voidwriteLines(File file, String encoding, Collection<?> lines, boolean append)Writes thetoString()value of each item in a collection to the specifiedFileline by line, optionally appending.static voidwriteLines(File file, String encoding, Collection<?> lines, String lineEnding)Writes thetoString()value of each item in a collection to the specifiedFileline by line.static voidwriteLines(File file, String encoding, Collection<?> lines, String lineEnding, boolean append)Writes thetoString()value of each item in a collection to the specifiedFileline by line.static voidwriteLines(File file, Collection<?> lines)Writes thetoString()value of each item in a collection to the specifiedFileline by line.static voidwriteLines(File file, Collection<?> lines, boolean append)Writes thetoString()value of each item in a collection to the specifiedFileline by line.static voidwriteLines(File file, Collection<?> lines, String lineEnding)Writes thetoString()value of each item in a collection to the specifiedFileline by line.static voidwriteLines(File file, Collection<?> lines, String lineEnding, boolean append)Writes thetoString()value of each item in a collection to the specifiedFileline by line.static voidwriteStringToFile(File file, String data)Writes a String to a file creating the file if it does not exist using the default encoding for the VM.static voidwriteStringToFile(File file, String data, boolean append)Writes a String to a file creating the file if it does not exist using the default encoding for the VM.static voidwriteStringToFile(File file, String data, String encoding)Writes a String to a file creating the file if it does not exist.static voidwriteStringToFile(File file, String data, String encoding, boolean append)Writes a String to a file creating the file if it does not exist.static voidwriteStringToFile(File file, String data, Charset encoding)Writes a String to a file creating the file if it does not exist.static voidwriteStringToFile(File file, String data, Charset encoding, boolean append)Writes a String to a file creating the file if it does not exist.
-
-
-
Field Detail
-
ONE_KB
public static final long ONE_KB
The number of bytes in a kilobyte.- See Also:
- Constant Field Values
-
ONE_KB_BI
public static final BigInteger ONE_KB_BI
The number of bytes in a kilobyte.- Since:
- 2.4
-
ONE_MB
public static final long ONE_MB
The number of bytes in a megabyte.- See Also:
- Constant Field Values
-
ONE_MB_BI
public static final BigInteger ONE_MB_BI
The number of bytes in a megabyte.- Since:
- 2.4
-
ONE_GB
public static final long ONE_GB
The number of bytes in a gigabyte.- See Also:
- Constant Field Values
-
ONE_GB_BI
public static final BigInteger ONE_GB_BI
The number of bytes in a gigabyte.- Since:
- 2.4
-
ONE_TB
public static final long ONE_TB
The number of bytes in a terabyte.- See Also:
- Constant Field Values
-
ONE_TB_BI
public static final BigInteger ONE_TB_BI
The number of bytes in a terabyte.- Since:
- 2.4
-
ONE_PB
public static final long ONE_PB
The number of bytes in a petabyte.- See Also:
- Constant Field Values
-
ONE_PB_BI
public static final BigInteger ONE_PB_BI
The number of bytes in a petabyte.- Since:
- 2.4
-
ONE_EB
public static final long ONE_EB
The number of bytes in an exabyte.- See Also:
- Constant Field Values
-
ONE_EB_BI
public static final BigInteger ONE_EB_BI
The number of bytes in an exabyte.- Since:
- 2.4
-
ONE_ZB
public static final BigInteger ONE_ZB
The number of bytes in a zettabyte.
-
ONE_YB
public static final BigInteger ONE_YB
The number of bytes in a yottabyte.
-
EMPTY_FILE_ARRAY
public static final File[] EMPTY_FILE_ARRAY
An empty array of typeFile.
-
-
Method Detail
-
getFile
public static File getFile(File directory, String... names)
Construct a file from the set of name elements.- Parameters:
directory- the parent directorynames- the name elements- Returns:
- the file
- Since:
- 2.1
-
getFile
public static File getFile(String... names)
Construct a file from the set of name elements.- Parameters:
names- the name elements- Returns:
- the file
- Since:
- 2.1
-
getTempDirectoryPath
public static String getTempDirectoryPath()
Returns the path to the system temporary directory.- Returns:
- the path to the system temporary directory.
- Since:
- 2.0
-
getTempDirectory
public static File getTempDirectory()
Returns aFilerepresenting the system temporary directory.- Returns:
- the system temporary directory.
- Since:
- 2.0
-
getUserDirectoryPath
public static String getUserDirectoryPath()
Returns the path to the user's home directory.- Returns:
- the path to the user's home directory.
- Since:
- 2.0
-
getUserDirectory
public static File getUserDirectory()
Returns aFilerepresenting the user's home directory.- Returns:
- the user's home directory.
- Since:
- 2.0
-
openInputStream
public static FileInputStream openInputStream(File file) throws IOException
Opens aFileInputStreamfor the specified file, providing better error messages than simply callingnew FileInputStream(file).At the end of the method either the stream will be successfully opened, or an exception will have been thrown.
An exception is thrown if the file does not exist. An exception is thrown if the file object exists but is a directory. An exception is thrown if the file exists but cannot be read.
- Parameters:
file- the file to open for input, must not benull- Returns:
- a new
FileInputStreamfor the specified file - Throws:
FileNotFoundException- if the file does not existIOException- if the file object is a directoryIOException- if the file cannot be read- Since:
- 1.3
-
openOutputStream
public static FileOutputStream openOutputStream(File file) throws IOException
Opens aFileOutputStreamfor the specified file, checking and creating the parent directory if it does not exist.At the end of the method either the stream will be successfully opened, or an exception will have been thrown.
The parent directory will be created if it does not exist. The file will be created if it does not exist. An exception is thrown if the file object exists but is a directory. An exception is thrown if the file exists but cannot be written to. An exception is thrown if the parent directory cannot be created.
- Parameters:
file- the file to open for output, must not benull- Returns:
- a new
FileOutputStreamfor the specified file - Throws:
IOException- if the file object is a directoryIOException- if the file cannot be written toIOException- if a parent directory needs creating but that fails- Since:
- 1.3
-
openOutputStream
public static FileOutputStream openOutputStream(File file, boolean append) throws IOException
Opens aFileOutputStreamfor the specified file, checking and creating the parent directory if it does not exist.At the end of the method either the stream will be successfully opened, or an exception will have been thrown.
The parent directory will be created if it does not exist. The file will be created if it does not exist. An exception is thrown if the file object exists but is a directory. An exception is thrown if the file exists but cannot be written to. An exception is thrown if the parent directory cannot be created.
- Parameters:
file- the file to open for output, must not benullappend- iftrue, then bytes will be added to the end of the file rather than overwriting- Returns:
- a new
FileOutputStreamfor the specified file - Throws:
IOException- if the file object is a directoryIOException- if the file cannot be written toIOException- if a parent directory needs creating but that fails- Since:
- 2.1
-
byteCountToDisplaySize
public static String byteCountToDisplaySize(BigInteger size)
Returns a human-readable version of the file size, where the input represents a specific number of bytes.If the size is over 1GB, the size is returned as the number of whole GB, i.e. the size is rounded down to the nearest GB boundary.
Similarly for the 1MB and 1KB boundaries.
- Parameters:
size- the number of bytes- Returns:
- a human-readable display value (includes units - EB, PB, TB, GB, MB, KB or bytes)
- Since:
- 2.4
- See Also:
- IO-226 - should the rounding be changed?
-
byteCountToDisplaySize
public static String byteCountToDisplaySize(long size)
Returns a human-readable version of the file size, where the input represents a specific number of bytes.If the size is over 1GB, the size is returned as the number of whole GB, i.e. the size is rounded down to the nearest GB boundary.
Similarly for the 1MB and 1KB boundaries.
- Parameters:
size- the number of bytes- Returns:
- a human-readable display value (includes units - EB, PB, TB, GB, MB, KB or bytes)
- See Also:
- IO-226 - should the rounding be changed?
-
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.NOTE: As from v1.3, this method throws an IOException if the last modified date of the file cannot be set. Also, as from v1.3 this method creates parent directories if they do not exist.
- Parameters:
file- the File to touch- Throws:
IOException- If an I/O problem occurs
-
convertFileCollectionToFileArray
public static File[] convertFileCollectionToFileArray(Collection<File> 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 Collection<File> listFiles(File directory, org.apache.commons.io.filefilter.IOFileFilter fileFilter, org.apache.commons.io.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 infileFilter- filter to apply when finding files.dirFilter- optional filter to apply when finding subdirectories. If this parameter isnull, 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
-
listFilesAndDirs
public static Collection<File> listFilesAndDirs(File directory, org.apache.commons.io.filefilter.IOFileFilter fileFilter, org.apache.commons.io.filefilter.IOFileFilter dirFilter)
Finds files within a given directory (and optionally its subdirectories). All files found are filtered by an IOFileFilter.The resulting collection includes the subdirectories themselves.
- Parameters:
directory- the directory to search infileFilter- filter to apply when finding files.dirFilter- optional filter to apply when finding subdirectories. If this parameter isnull, 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
- Since:
- 2.2
- See Also:
FileUtils.listFiles(java.io.File, org.apache.commons.io.filefilter.IOFileFilter, org.apache.commons.io.filefilter.IOFileFilter),FileFilterUtils,NameFileFilter
-
iterateFiles
public static Iterator<File> iterateFiles(File directory, org.apache.commons.io.filefilter.IOFileFilter fileFilter, org.apache.commons.io.filefilter.IOFileFilter dirFilter)
Allows iteration over the files in given directory (and optionally its subdirectories).All files found are filtered by an IOFileFilter. This method is based on
listFiles(File, IOFileFilter, IOFileFilter), which supports Iterable ('foreach' loop).- Parameters:
directory- the directory to search infileFilter- filter to apply when finding files.dirFilter- optional filter to apply when finding subdirectories. If this parameter isnull, subdirectories will not be included in the search. Use TrueFileFilter.INSTANCE to match all directories.- Returns:
- an iterator of java.io.File for the matching files
- Since:
- 1.2
- See Also:
FileFilterUtils,NameFileFilter
-
iterateFilesAndDirs
public static Iterator<File> iterateFilesAndDirs(File directory, org.apache.commons.io.filefilter.IOFileFilter fileFilter, org.apache.commons.io.filefilter.IOFileFilter dirFilter)
Allows iteration over the files in given directory (and optionally its subdirectories).All files found are filtered by an IOFileFilter. This method is based on
listFilesAndDirs(File, IOFileFilter, IOFileFilter), which supports Iterable ('foreach' loop).The resulting iterator includes the subdirectories themselves.
- Parameters:
directory- the directory to search infileFilter- filter to apply when finding files.dirFilter- optional filter to apply when finding subdirectories. If this parameter isnull, subdirectories will not be included in the search. Use TrueFileFilter.INSTANCE to match all directories.- Returns:
- an iterator of java.io.File for the matching files
- Since:
- 2.2
- See Also:
FileFilterUtils,NameFileFilter
-
listFiles
public static Collection<File> 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 inextensions- an array of extensions, ex. {"java","xml"}. If this parameter isnull, all files are returned.recursive- if true all subdirectories are searched as well- Returns:
- an collection of java.io.File with the matching files
-
iterateFiles
public static Iterator<File> iterateFiles(File directory, String[] extensions, boolean recursive)
Allows iteration over the files in a given directory (and optionally its subdirectories) which match an array of extensions. This method is based onlistFiles(File, String[], boolean), which supports Iterable ('foreach' loop).- Parameters:
directory- the directory to search inextensions- an array of extensions, ex. {"java","xml"}. If this parameter isnull, all files are returned.recursive- if true all subdirectories are searched as well- Returns:
- an iterator of java.io.File with the matching files
- Since:
- 1.2
-
contentEquals
public static boolean contentEquals(File file1, File file2) throws IOException
Compares the contents of two files to determine if they are equal or not.This method checks to see if the two files are different lengths or if they point to the same file, before resorting to byte-by-byte comparison of the contents.
Code origin: Avalon
- Parameters:
file1- the first filefile2- the second file- Returns:
- true if the content of the files are equal or they both don't exist, false otherwise
- Throws:
IOException- in case of an I/O error
-
contentEqualsIgnoreEOL
public static boolean contentEqualsIgnoreEOL(File file1, File file2, String charsetName) throws IOException
Compares the contents of two files to determine if they are equal or not.This method checks to see if the two files point to the same file, before resorting to line-by-line comparison of the contents.
- Parameters:
file1- the first filefile2- the second filecharsetName- the character encoding to be used. May be null, in which case the platform default is used- Returns:
- true if the content of the files are equal or neither exists, false otherwise
- Throws:
IOException- in case of an I/O error- Since:
- 2.2
- See Also:
IOUtils.contentEqualsIgnoreEOL(Reader, Reader)
-
toFile
public static File toFile(URL url)
Convert from aURLto aFile.From version 1.1 this method will decode the URL. Syntax such as
file:///my%20docs/file.txtwill be correctly decoded to/my docs/file.txt. Starting with version 1.5, this method uses UTF-8 to decode percent-encoded octets to characters. Additionally, malformed percent-encoded octets are handled leniently by passing them through literally.- Parameters:
url- the file URL to convert,nullreturnsnull- Returns:
- the equivalent
Fileobject, ornullif the URL's protocol is notfile
-
toFiles
public static File[] toFiles(URL[] urls)
Converts each of an array ofURLto aFile.Returns an array of the same size as the input. If the input is
null, an empty array is returned. If the input containsnull, the output array containsnullat the same index.This method will decode the URL. Syntax such as
file:///my%20docs/file.txtwill be correctly decoded to/my docs/file.txt.- Parameters:
urls- the file URLs to convert,nullreturns empty array- Returns:
- a non-
nullarray of Files matching the input, with anullitem if there was anullat that index in the input array - Throws:
IllegalArgumentException- if any file is not a URL fileIllegalArgumentException- if any file is incorrectly encoded- Since:
- 1.1
-
toURLs
public static URL[] toURLs(File[] files) throws IOException
Converts each of an array ofFileto aURL.Returns an array of the same size as the input.
- Parameters:
files- the files to convert, must not benull- Returns:
- an array of URLs matching the input
- Throws:
IOException- if a file cannot be convertedNullPointerException- if the parameter is null
-
copyFileToDirectory
public static void copyFileToDirectory(File srcFile, File destDir) throws IOException
Copies a file to a directory preserving the file date.This method copies the contents of the specified source file to a file of the same name in the specified destination directory. The destination directory is created if it does not exist. If the destination file exists, then this method will overwrite it.
Note: This method tries to preserve the file's last modified date/times using
File.setLastModified(long), however it is not guaranteed that the operation will succeed. If the modification operation fails, no indication is provided.- Parameters:
srcFile- an existing file to copy, must not benulldestDir- the directory to place the copy in, must not benull- Throws:
NullPointerException- if source or destination is nullIOException- if source or destination is invalidIOException- if an IO error occurs during copying- See Also:
copyFile(File, File, boolean)
-
copyFileToDirectory
public static void copyFileToDirectory(File srcFile, File destDir, boolean preserveFileDate) throws IOException
Copies a file to a directory optionally preserving the file date.This method copies the contents of the specified source file to a file of the same name in the specified destination directory. The destination directory is created if it does not exist. If the destination file exists, then this method will overwrite it.
Note: Setting
preserveFileDatetotruetries to preserve the file's last modified date/times usingFile.setLastModified(long), however it is not guaranteed that the operation will succeed. If the modification operation fails, no indication is provided.- Parameters:
srcFile- an existing file to copy, must not benulldestDir- the directory to place the copy in, must not benullpreserveFileDate- true if the file date of the copy should be the same as the original- Throws:
NullPointerException- if source or destination isnullIOException- if source or destination is invalidIOException- if an IO error occurs during copying- Since:
- 1.3
- See Also:
copyFile(File, File, boolean)
-
copyFile
public static void copyFile(File srcFile, File destFile) throws IOException
Copies a file to a new location preserving the file date.This method copies the contents of the specified source file to the specified destination file. The directory holding the destination file is created if it does not exist. If the destination file exists, then this method will overwrite it.
Note: This method tries to preserve the file's last modified date/times using
File.setLastModified(long), however it is not guaranteed that the operation will succeed. If the modification operation fails, no indication is provided.- Parameters:
srcFile- an existing file to copy, must not benulldestFile- the new file, must not benull- Throws:
NullPointerException- if source or destination isnullIOException- if source or destination is invalidIOException- if an IO error occurs during copying- See Also:
copyFileToDirectory(File, File)
-
copyFile
public static void copyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException
Copies a file to a new location.This method copies the contents of the specified source file to the specified destination file. The directory holding the destination file is created if it does not exist. If the destination file exists, then this method will overwrite it.
Note: Setting
preserveFileDatetotruetries to preserve the file's last modified date/times usingFile.setLastModified(long), however it is not guaranteed that the operation will succeed. If the modification operation fails, no indication is provided.- Parameters:
srcFile- an existing file to copy, must not benulldestFile- the new file, must not benullpreserveFileDate- true if the file date of the copy should be the same as the original- Throws:
NullPointerException- if source or destination isnullIOException- if source or destination is invalidIOException- if an IO error occurs during copying- See Also:
copyFileToDirectory(File, File, boolean)
-
copyFile
public static long copyFile(File input, OutputStream output) throws IOException
Copy bytes from aFileto anOutputStream.This method buffers the input internally, so there is no need to use a
BufferedInputStream.- Parameters:
input- theFileto read fromoutput- theOutputStreamto write to- Returns:
- the number of bytes copied
- Throws:
NullPointerException- if the input or output is nullIOException- if an I/O error occurs- Since:
- 2.1
-
copyDirectoryToDirectory
public static void copyDirectoryToDirectory(File srcDir, File destDir) throws IOException
Copies a directory to within another directory preserving the file dates.This method copies the source directory and all its contents to a directory of the same name in the specified destination directory.
The destination directory is created if it does not exist. If the destination directory did exist, then this method merges the source with the destination, with the source taking precedence.
Note: This method tries to preserve the files' last modified date/times using
File.setLastModified(long), however it is not guaranteed that those operations will succeed. If the modification operation fails, no indication is provided.- Parameters:
srcDir- an existing directory to copy, must not benulldestDir- the directory to place the copy in, must not benull- Throws:
NullPointerException- if source or destination isnullIOException- if source or destination is invalidIOException- if an IO error occurs during copying- Since:
- 1.2
-
copyDirectory
public static void copyDirectory(File srcDir, File destDir) throws IOException
Copies a whole directory to a new location preserving the file dates.This method copies the specified directory and all its child directories and files to the specified destination. The destination is the new location and name of the directory.
The destination directory is created if it does not exist. If the destination directory did exist, then this method merges the source with the destination, with the source taking precedence.
Note: This method tries to preserve the files' last modified date/times using
File.setLastModified(long), however it is not guaranteed that those operations will succeed. If the modification operation fails, no indication is provided.- Parameters:
srcDir- an existing directory to copy, must not benulldestDir- the new directory, must not benull- Throws:
NullPointerException- if source or destination isnullIOException- if source or destination is invalidIOException- if an IO error occurs during copying- Since:
- 1.1
-
copyDirectory
public static void copyDirectory(File srcDir, File destDir, boolean preserveFileDate) throws IOException
Copies a whole directory to a new location.This method copies the contents of the specified source directory to within the specified destination directory.
The destination directory is created if it does not exist. If the destination directory did exist, then this method merges the source with the destination, with the source taking precedence.
Note: Setting
preserveFileDatetotruetries to preserve the files' last modified date/times usingFile.setLastModified(long), however it is not guaranteed that those operations will succeed. If the modification operation fails, no indication is provided.- Parameters:
srcDir- an existing directory to copy, must not benulldestDir- the new directory, must not benullpreserveFileDate- true if the file date of the copy should be the same as the original- Throws:
NullPointerException- if source or destination isnullIOException- if source or destination is invalidIOException- if an IO error occurs during copying- Since:
- 1.1
-
copyDirectory
public static void copyDirectory(File srcDir, File destDir, FileFilter filter) throws IOException
Copies a filtered directory to a new location preserving the file dates.This method copies the contents of the specified source directory to within the specified destination directory.
The destination directory is created if it does not exist. If the destination directory did exist, then this method merges the source with the destination, with the source taking precedence.
Note: This method tries to preserve the files' last modified date/times using
File.setLastModified(long), however it is not guaranteed that those operations will succeed. If the modification operation fails, no indication is provided.Example: Copy directories only
// only copy the directory structure FileUtils.copyDirectory(srcDir, destDir, DirectoryFileFilter.DIRECTORY);
Example: Copy directories and txt files
// Create a filter for ".txt" files IOFileFilter txtSuffixFilter = FileFilterUtils.suffixFileFilter(".txt"); IOFileFilter txtFiles = FileFilterUtils.andFileFilter(FileFileFilter.FILE, txtSuffixFilter); // Create a filter for either directories or ".txt" files FileFilter filter = FileFilterUtils.orFileFilter(DirectoryFileFilter.DIRECTORY, txtFiles); // Copy using the filter FileUtils.copyDirectory(srcDir, destDir, filter);- Parameters:
srcDir- an existing directory to copy, must not benulldestDir- the new directory, must not benullfilter- the filter to apply, null means copy all directories and files should be the same as the original- Throws:
NullPointerException- if source or destination isnullIOException- if source or destination is invalidIOException- if an IO error occurs during copying- Since:
- 1.4
-
copyDirectory
public static void copyDirectory(File srcDir, File destDir, FileFilter filter, boolean preserveFileDate) throws IOException
Copies a filtered directory to a new location.This method copies the contents of the specified source directory to within the specified destination directory.
The destination directory is created if it does not exist. If the destination directory did exist, then this method merges the source with the destination, with the source taking precedence.
Note: Setting
preserveFileDatetotruetries to preserve the files' last modified date/times usingFile.setLastModified(long), however it is not guaranteed that those operations will succeed. If the modification operation fails, no indication is provided.Example: Copy directories only
// only copy the directory structure FileUtils.copyDirectory(srcDir, destDir, DirectoryFileFilter.DIRECTORY, false);
Example: Copy directories and txt files
// Create a filter for ".txt" files IOFileFilter txtSuffixFilter = FileFilterUtils.suffixFileFilter(".txt"); IOFileFilter txtFiles = FileFilterUtils.andFileFilter(FileFileFilter.FILE, txtSuffixFilter); // Create a filter for either directories or ".txt" files FileFilter filter = FileFilterUtils.orFileFilter(DirectoryFileFilter.DIRECTORY, txtFiles); // Copy using the filter FileUtils.copyDirectory(srcDir, destDir, filter, false);- Parameters:
srcDir- an existing directory to copy, must not benulldestDir- the new directory, must not benullfilter- the filter to apply, null means copy all directories and filespreserveFileDate- true if the file date of the copy should be the same as the original- Throws:
NullPointerException- if source or destination isnullIOException- if source or destination is invalidIOException- if an IO error occurs during copying- Since:
- 1.4
-
copyURLToFile
public static void copyURLToFile(URL source, File destination) throws IOException
Copies bytes from the URLsourceto a filedestination. The directories up todestinationwill be created if they don't already exist.destinationwill be overwritten if it already exists.Warning: this method does not set a connection or read timeout and thus might block forever. Use
copyURLToFile(URL, File, int, int)with reasonable timeouts to prevent this.- Parameters:
source- theURLto copy bytes from, must not benulldestination- the non-directoryFileto write bytes to (possibly overwriting), must not benull- Throws:
IOException- ifsourceURL cannot be openedIOException- ifdestinationis a directoryIOException- ifdestinationcannot be writtenIOException- ifdestinationneeds creating but can't beIOException- if an IO error occurs during copying
-
copyURLToFile
public static void copyURLToFile(URL source, File destination, int connectionTimeout, int readTimeout) throws IOException
Copies bytes from the URLsourceto a filedestination. The directories up todestinationwill be created if they don't already exist.destinationwill be overwritten if it already exists.- Parameters:
source- theURLto copy bytes from, must not benulldestination- the non-directoryFileto write bytes to (possibly overwriting), must not benullconnectionTimeout- the number of milliseconds until this method will timeout if no connection could be established to thesourcereadTimeout- the number of milliseconds until this method will timeout if no data could be read from thesource- Throws:
IOException- ifsourceURL cannot be openedIOException- ifdestinationis a directoryIOException- ifdestinationcannot be writtenIOException- ifdestinationneeds creating but can't beIOException- if an IO error occurs during copying- Since:
- 2.0
-
copyInputStreamToFile
public static void copyInputStreamToFile(InputStream source, File destination) throws IOException
Copies bytes from anInputStreamsourceto a filedestination. The directories up todestinationwill be created if they don't already exist.destinationwill be overwritten if it already exists.- Parameters:
source- theInputStreamto copy bytes from, must not benulldestination- the non-directoryFileto write bytes to (possibly overwriting), must not benull- Throws:
IOException- ifdestinationis a directoryIOException- ifdestinationcannot be writtenIOException- ifdestinationneeds creating but can't beIOException- if an IO error occurs during copying- Since:
- 2.0
-
deleteDirectory
public static void deleteDirectory(File directory) throws IOException
Deletes a directory recursively.- Parameters:
directory- directory to delete- Throws:
IOException- in case deletion is unsuccessful
-
deleteQuietly
public static boolean deleteQuietly(File file)
Deletes a file, never throwing an exception. 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.
- No exceptions are thrown when a file or directory cannot be deleted.
- Parameters:
file- file or directory to delete, can benull- Returns:
trueif the file or directory was deleted, otherwisefalse- Since:
- 1.4
-
directoryContains
public static boolean directoryContains(File directory, File child) throws IOException
Determines whether theparentdirectory contains thechildelement (a file or directory).Files are normalized before comparison.
Edge cases:- A
directorymust not be null: if null, throw IllegalArgumentException - A
directorymust be a directory: if not a directory, throw IllegalArgumentException - A directory does not contain itself: return false
- A null child file is not contained in any parent: return false
- Parameters:
directory- the file to consider as the parent.child- the file to consider as the child.- Returns:
- true is the candidate leaf is under by the specified composite. False otherwise.
- Throws:
IOException- if an IO error occurs while checking the files.- Since:
- 2.2
- See Also:
FilenameUtils.directoryContains(String, String)
- A
-
cleanDirectory
public static void cleanDirectory(File directory) throws IOException
Cleans a directory without deleting it.- Parameters:
directory- directory to clean- Throws:
IOException- in case cleaning is unsuccessful
-
waitFor
public static boolean waitFor(File file, int seconds)
Waits for NFS to propagate a file creation, imposing a timeout.This method repeatedly tests
File.exists()until it returns true up to the maximum time specified in seconds.- Parameters:
file- the file to check, must not benullseconds- the maximum time in seconds to wait- Returns:
- true if file exists
- Throws:
NullPointerException- if the file isnull
-
readFileToString
public static String readFileToString(File file, Charset encoding) throws IOException
Reads the contents of a file into a String. The file is always closed.- Parameters:
file- the file to read, must not benullencoding- the encoding to use,nullmeans platform default- Returns:
- the file contents, never
null - Throws:
IOException- in case of an I/O error- Since:
- 2.3
-
readFileToString
public static String readFileToString(File file, String encoding) throws IOException
Reads the contents of a file into a String. The file is always closed.- Parameters:
file- the file to read, must not benullencoding- the encoding to use,nullmeans platform default- Returns:
- the file contents, never
null - Throws:
IOException- in case of an I/O errorUnsupportedCharsetException- thrown instead ofUnsupportedEncodingExceptionin version 2.2 if the encoding is not supported.- Since:
- 2.3
-
readFileToString
public static String readFileToString(File file) throws IOException
Reads the contents of a file into a String using the default encoding for the VM. The file is always closed.- Parameters:
file- the file to read, must not benull- Returns:
- the file contents, never
null - Throws:
IOException- in case of an I/O error- Since:
- 1.3.1
-
readFileToByteArray
public static byte[] readFileToByteArray(File file) throws IOException
Reads the contents of a file into a byte array. The file is always closed.- Parameters:
file- the file to read, must not benull- Returns:
- the file contents, never
null - Throws:
IOException- in case of an I/O error- Since:
- 1.1
-
readLines
public static List<String> readLines(File file, Charset encoding) throws IOException
Reads the contents of a file line by line to a List of Strings. The file is always closed.- Parameters:
file- the file to read, must not benullencoding- the encoding to use,nullmeans platform default- Returns:
- the list of Strings representing each line in the file, never
null - Throws:
IOException- in case of an I/O error- Since:
- 2.3
-
readLines
public static List<String> readLines(File file, String encoding) throws IOException
Reads the contents of a file line by line to a List of Strings. The file is always closed.- Parameters:
file- the file to read, must not benullencoding- the encoding to use,nullmeans platform default- Returns:
- the list of Strings representing each line in the file, never
null - Throws:
IOException- in case of an I/O errorUnsupportedCharsetException- thrown instead ofUnsupportedEncodingExceptionin version 2.2 if the encoding is not supported.- Since:
- 1.1
-
readLines
public static List<String> readLines(File file) throws IOException
Reads the contents of a file line by line to a List of Strings using the default encoding for the VM. The file is always closed.- Parameters:
file- the file to read, must not benull- Returns:
- the list of Strings representing each line in the file, never
null - Throws:
IOException- in case of an I/O error- Since:
- 1.3
-
lineIterator
public static org.apache.commons.io.LineIterator lineIterator(File file, String encoding) throws IOException
Returns an Iterator for the lines in aFile.This method opens an
InputStreamfor the file. When you have finished with the iterator you should close the stream to free internal resources. This can be done by calling theLineIterator.close()orLineIterator.closeQuietly(LineIterator)method.The recommended usage pattern is:
LineIterator it = FileUtils.lineIterator(file, "UTF-8"); try { while (it.hasNext()) { String line = it.nextLine(); /// do something with line } } finally { LineIterator.closeQuietly(iterator); }If an exception occurs during the creation of the iterator, the underlying stream is closed.
- Parameters:
file- the file to open for input, must not benullencoding- the encoding to use,nullmeans platform default- Returns:
- an Iterator of the lines in the file, never
null - Throws:
IOException- in case of an I/O error (file closed)- Since:
- 1.2
-
lineIterator
public static org.apache.commons.io.LineIterator lineIterator(File file) throws IOException
Returns an Iterator for the lines in aFileusing the default encoding for the VM.- Parameters:
file- the file to open for input, must not benull- Returns:
- an Iterator of the lines in the file, never
null - Throws:
IOException- in case of an I/O error (file closed)- Since:
- 1.3
- See Also:
lineIterator(File, String)
-
writeStringToFile
public static void writeStringToFile(File file, String data, Charset encoding) throws IOException
Writes a String to a file creating the file if it does not exist. NOTE: As from v1.3, the parent directories of the file will be created if they do not exist.- Parameters:
file- the file to writedata- the content to write to the fileencoding- the encoding to use,nullmeans platform default- Throws:
IOException- in case of an I/O errorUnsupportedEncodingException- if the encoding is not supported by the VM- Since:
- 2.4
-
writeStringToFile
public static void writeStringToFile(File file, String data, String encoding) throws IOException
Writes a String to a file creating the file if it does not exist. NOTE: As from v1.3, the parent directories of the file will be created if they do not exist.- Parameters:
file- the file to writedata- the content to write to the fileencoding- the encoding to use,nullmeans platform default- Throws:
IOException- in case of an I/O errorUnsupportedEncodingException- if the encoding is not supported by the VM
-
writeStringToFile
public static void writeStringToFile(File file, String data, Charset encoding, boolean append) throws IOException
Writes a String to a file creating the file if it does not exist.- Parameters:
file- the file to writedata- the content to write to the fileencoding- the encoding to use,nullmeans platform defaultappend- iftrue, then the String will be added to the end of the file rather than overwriting- Throws:
IOException- in case of an I/O error- Since:
- 2.3
-
writeStringToFile
public static void writeStringToFile(File file, String data, String encoding, boolean append) throws IOException
Writes a String to a file creating the file if it does not exist.- Parameters:
file- the file to writedata- the content to write to the fileencoding- the encoding to use,nullmeans platform defaultappend- iftrue, then the String will be added to the end of the file rather than overwriting- Throws:
IOException- in case of an I/O errorUnsupportedCharsetException- thrown instead ofUnsupportedEncodingExceptionin version 2.2 if the encoding is not supported by the VM- Since:
- 2.1
-
writeStringToFile
public static void writeStringToFile(File file, String data) throws IOException
Writes a String to a file creating the file if it does not exist using the default encoding for the VM.- Parameters:
file- the file to writedata- the content to write to the file- Throws:
IOException- in case of an I/O error
-
writeStringToFile
public static void writeStringToFile(File file, String data, boolean append) throws IOException
Writes a String to a file creating the file if it does not exist using the default encoding for the VM.- Parameters:
file- the file to writedata- the content to write to the fileappend- iftrue, then the String will be added to the end of the file rather than overwriting- Throws:
IOException- in case of an I/O error- Since:
- 2.1
-
write
public static void write(File file, CharSequence data) throws IOException
Writes a CharSequence to a file creating the file if it does not exist using the default encoding for the VM.- Parameters:
file- the file to writedata- the content to write to the file- Throws:
IOException- in case of an I/O error- Since:
- 2.0
-
write
public static void write(File file, CharSequence data, boolean append) throws IOException
Writes a CharSequence to a file creating the file if it does not exist using the default encoding for the VM.- Parameters:
file- the file to writedata- the content to write to the fileappend- iftrue, then the data will be added to the end of the file rather than overwriting- Throws:
IOException- in case of an I/O error- Since:
- 2.1
-
write
public static void write(File file, CharSequence data, Charset encoding) throws IOException
Writes a CharSequence to a file creating the file if it does not exist.- Parameters:
file- the file to writedata- the content to write to the fileencoding- the encoding to use,nullmeans platform default- Throws:
IOException- in case of an I/O error- Since:
- 2.3
-
write
public static void write(File file, CharSequence data, String encoding) throws IOException
Writes a CharSequence to a file creating the file if it does not exist.- Parameters:
file- the file to writedata- the content to write to the fileencoding- the encoding to use,nullmeans platform default- Throws:
IOException- in case of an I/O errorUnsupportedEncodingException- if the encoding is not supported by the VM- Since:
- 2.0
-
write
public static void write(File file, CharSequence data, Charset encoding, boolean append) throws IOException
Writes a CharSequence to a file creating the file if it does not exist.- Parameters:
file- the file to writedata- the content to write to the fileencoding- the encoding to use,nullmeans platform defaultappend- iftrue, then the data will be added to the end of the file rather than overwriting- Throws:
IOException- in case of an I/O error- Since:
- 2.3
-
write
public static void write(File file, CharSequence data, String encoding, boolean append) throws IOException
Writes a CharSequence to a file creating the file if it does not exist.- Parameters:
file- the file to writedata- the content to write to the fileencoding- the encoding to use,nullmeans platform defaultappend- iftrue, then the data will be added to the end of the file rather than overwriting- Throws:
IOException- in case of an I/O errorUnsupportedCharsetException- thrown instead ofUnsupportedEncodingExceptionin version 2.2 if the encoding is not supported by the VM- Since:
- IO 2.1
-
writeByteArrayToFile
public static void writeByteArrayToFile(File file, byte[] data) throws IOException
Writes a byte array to a file creating the file if it does not exist.NOTE: As from v1.3, the parent directories of the file will be created if they do not exist.
- Parameters:
file- the file to write todata- the content to write to the file- Throws:
IOException- in case of an I/O error- Since:
- 1.1
-
writeByteArrayToFile
public static void writeByteArrayToFile(File file, byte[] data, boolean append) throws IOException
Writes a byte array to a file creating the file if it does not exist.- Parameters:
file- the file to write todata- the content to write to the fileappend- iftrue, then bytes will be added to the end of the file rather than overwriting- Throws:
IOException- in case of an I/O error- Since:
- IO 2.1
-
writeLines
public static void writeLines(File file, String encoding, Collection<?> lines) throws IOException
Writes thetoString()value of each item in a collection to the specifiedFileline by line. The specified character encoding and the default line ending will be used.NOTE: As from v1.3, the parent directories of the file will be created if they do not exist.
- Parameters:
file- the file to write toencoding- the encoding to use,nullmeans platform defaultlines- the lines to write,nullentries produce blank lines- Throws:
IOException- in case of an I/O errorUnsupportedEncodingException- if the encoding is not supported by the VM- Since:
- 1.1
-
writeLines
public static void writeLines(File file, String encoding, Collection<?> lines, boolean append) throws IOException
Writes thetoString()value of each item in a collection to the specifiedFileline by line, optionally appending. The specified character encoding and the default line ending will be used.- Parameters:
file- the file to write toencoding- the encoding to use,nullmeans platform defaultlines- the lines to write,nullentries produce blank linesappend- iftrue, then the lines will be added to the end of the file rather than overwriting- Throws:
IOException- in case of an I/O errorUnsupportedEncodingException- if the encoding is not supported by the VM- Since:
- 2.1
-
writeLines
public static void writeLines(File file, Collection<?> lines) throws IOException
Writes thetoString()value of each item in a collection to the specifiedFileline by line. The default VM encoding and the default line ending will be used.- Parameters:
file- the file to write tolines- the lines to write,nullentries produce blank lines- Throws:
IOException- in case of an I/O error- Since:
- 1.3
-
writeLines
public static void writeLines(File file, Collection<?> lines, boolean append) throws IOException
Writes thetoString()value of each item in a collection to the specifiedFileline by line. The default VM encoding and the default line ending will be used.- Parameters:
file- the file to write tolines- the lines to write,nullentries produce blank linesappend- iftrue, then the lines will be added to the end of the file rather than overwriting- Throws:
IOException- in case of an I/O error- Since:
- 2.1
-
writeLines
public static void writeLines(File file, String encoding, Collection<?> lines, String lineEnding) throws IOException
Writes thetoString()value of each item in a collection to the specifiedFileline by line. The specified character encoding and the line ending will be used.NOTE: As from v1.3, the parent directories of the file will be created if they do not exist.
- Parameters:
file- the file to write toencoding- the encoding to use,nullmeans platform defaultlines- the lines to write,nullentries produce blank lineslineEnding- the line separator to use,nullis system default- Throws:
IOException- in case of an I/O errorUnsupportedEncodingException- if the encoding is not supported by the VM- Since:
- 1.1
-
writeLines
public static void writeLines(File file, String encoding, Collection<?> lines, String lineEnding, boolean append) throws IOException
Writes thetoString()value of each item in a collection to the specifiedFileline by line. The specified character encoding and the line ending will be used.- Parameters:
file- the file to write toencoding- the encoding to use,nullmeans platform defaultlines- the lines to write,nullentries produce blank lineslineEnding- the line separator to use,nullis system defaultappend- iftrue, then the lines will be added to the end of the file rather than overwriting- Throws:
IOException- in case of an I/O errorUnsupportedEncodingException- if the encoding is not supported by the VM- Since:
- 2.1
-
writeLines
public static void writeLines(File file, Collection<?> lines, String lineEnding) throws IOException
Writes thetoString()value of each item in a collection to the specifiedFileline by line. The default VM encoding and the specified line ending will be used.- Parameters:
file- the file to write tolines- the lines to write,nullentries produce blank lineslineEnding- the line separator to use,nullis system default- Throws:
IOException- in case of an I/O error- Since:
- 1.3
-
writeLines
public static void writeLines(File file, Collection<?> lines, String lineEnding, boolean append) throws IOException
Writes thetoString()value of each item in a collection to the specifiedFileline by line. The default VM encoding and the specified line ending will be used.- Parameters:
file- the file to write tolines- the lines to write,nullentries produce blank lineslineEnding- the line separator to use,nullis system defaultappend- iftrue, then the lines will be added to the end of the file rather than overwriting- Throws:
IOException- in case of an I/O error- Since:
- 2.1
-
forceDelete
public static void forceDelete(File file) throws IOException
Deletes 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, must not benull- Throws:
NullPointerException- if the directory isnullFileNotFoundException- if the file was not foundIOException- in case deletion is unsuccessful
-
forceDeleteOnExit
public static void forceDeleteOnExit(File file) throws IOException
Schedules 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, must not benull- Throws:
NullPointerException- if the file isnullIOException- in case deletion is unsuccessful
-
forceMkdir
public static void forceMkdir(File directory) throws IOException
Makes a directory, including any necessary but nonexistent parent directories. If a file already exists with specified name but it is not a directory then an IOException is thrown. If the directory cannot be created (or does not already exist) then an IOException is thrown.- Parameters:
directory- directory to create, must not benull- Throws:
NullPointerException- if the directory isnullIOException- if the directory cannot be created or the file already exists but is not a directory
-
sizeOf
public static long sizeOf(File file)
Returns the size of the specified file or directory. If the providedFileis a regular file, then the file's length is returned. If the argument is a directory, then the size of the directory is calculated recursively. If a directory or subdirectory is security restricted, its size will not be included.- Parameters:
file- the regular file or directory to return the size of (must not benull).- Returns:
- the length of the file, or recursive size of the directory, provided (in bytes).
- Throws:
NullPointerException- if the file isnullIllegalArgumentException- if the file does not exist.- Since:
- 2.0
-
sizeOfAsBigInteger
public static BigInteger sizeOfAsBigInteger(File file)
Returns the size of the specified file or directory. If the providedFileis a regular file, then the file's length is returned. If the argument is a directory, then the size of the directory is calculated recursively. If a directory or subdirectory is security restricted, its size will not be included.- Parameters:
file- the regular file or directory to return the size of (must not benull).- Returns:
- the length of the file, or recursive size of the directory, provided (in bytes).
- Throws:
NullPointerException- if the file isnullIllegalArgumentException- if the file does not exist.- Since:
- 2.4
-
sizeOfDirectory
public static long sizeOfDirectory(File directory)
Counts the size of a directory recursively (sum of the length of all files).- Parameters:
directory- directory to inspect, must not benull- Returns:
- size of directory in bytes, 0 if directory is security restricted, a negative number when the real total
is greater than
Long.MAX_VALUE. - Throws:
NullPointerException- if the directory isnull
-
sizeOfDirectoryAsBigInteger
public static BigInteger sizeOfDirectoryAsBigInteger(File directory)
Counts the size of a directory recursively (sum of the length of all files).- Parameters:
directory- directory to inspect, must not benull- Returns:
- size of directory in bytes, 0 if directory is security restricted.
- Throws:
NullPointerException- if the directory isnull- Since:
- 2.4
-
isFileNewer
public static boolean isFileNewer(File file, File reference)
Tests if the specifiedFileis newer than the referenceFile.- Parameters:
file- theFileof which the modification date must be compared, must not benullreference- theFileof which the modification date is used, must not benull- Returns:
- true if the
Fileexists and has been modified more recently than the referenceFile - Throws:
IllegalArgumentException- if the file isnullIllegalArgumentException- if the reference file isnullor doesn't exist
-
isFileNewer
public static boolean isFileNewer(File file, Date date)
Tests if the specifiedFileis newer than the specifiedDate.- Parameters:
file- theFileof which the modification date must be compared, must not benulldate- the date reference, must not benull- Returns:
- true if the
Fileexists and has been modified after the givenDate. - Throws:
IllegalArgumentException- if the file isnullIllegalArgumentException- if the date isnull
-
isFileNewer
public static boolean isFileNewer(File file, long timeMillis)
Tests if the specifiedFileis newer than the specified time reference.- Parameters:
file- theFileof which the modification date must be compared, must not benulltimeMillis- the time reference measured in milliseconds since the epoch (00:00:00 GMT, January 1, 1970)- Returns:
- true if the
Fileexists and has been modified after the given time reference. - Throws:
IllegalArgumentException- if the file isnull
-
isFileOlder
public static boolean isFileOlder(File file, File reference)
Tests if the specifiedFileis older than the referenceFile.- Parameters:
file- theFileof which the modification date must be compared, must not benullreference- theFileof which the modification date is used, must not benull- Returns:
- true if the
Fileexists and has been modified before the referenceFile - Throws:
IllegalArgumentException- if the file isnullIllegalArgumentException- if the reference file isnullor doesn't exist
-
isFileOlder
public static boolean isFileOlder(File file, Date date)
Tests if the specifiedFileis older than the specifiedDate.- Parameters:
file- theFileof which the modification date must be compared, must not benulldate- the date reference, must not benull- Returns:
- true if the
Fileexists and has been modified before the givenDate. - Throws:
IllegalArgumentException- if the file isnullIllegalArgumentException- if the date isnull
-
isFileOlder
public static boolean isFileOlder(File file, long timeMillis)
Tests if the specifiedFileis older than the specified time reference.- Parameters:
file- theFileof which the modification date must be compared, must not benulltimeMillis- the time reference measured in milliseconds since the epoch (00:00:00 GMT, January 1, 1970)- Returns:
- true if the
Fileexists and has been modified before the given time reference. - Throws:
IllegalArgumentException- if the file isnull
-
checksumCRC32
public static long checksumCRC32(File file) throws IOException
Computes the checksum of a file using the CRC32 checksum routine. The value of the checksum is returned.- Parameters:
file- the file to checksum, must not benull- Returns:
- the checksum value
- Throws:
NullPointerException- if the file or checksum isnullIllegalArgumentException- if the file is a directoryIOException- if an IO error occurs reading the file- Since:
- 1.3
-
checksum
public static Checksum checksum(File file, Checksum checksum) throws IOException
Computes the checksum of a file using the specified checksum object. Multiple files may be checked using oneChecksuminstance if desired simply by reusing the same checksum object. For example:long csum = FileUtils.checksum(file, new CRC32()).getValue();
- Parameters:
file- the file to checksum, must not benullchecksum- the checksum object to be used, must not benull- Returns:
- the checksum specified, updated with the content of the file
- Throws:
NullPointerException- if the file or checksum isnullIllegalArgumentException- if the file is a directoryIOException- if an IO error occurs reading the file- Since:
- 1.3
-
moveDirectory
public static void moveDirectory(File srcDir, File destDir) throws IOException
Moves a directory.When the destination directory is on another file system, do a "copy and delete".
- Parameters:
srcDir- the directory to be moveddestDir- the destination directory- Throws:
NullPointerException- if source or destination isnullorg.apache.commons.io.FileExistsException- if the destination directory existsIOException- if source or destination is invalidIOException- if an IO error occurs moving the file- Since:
- 1.4
-
moveDirectoryToDirectory
public static void moveDirectoryToDirectory(File src, File destDir, boolean createDestDir) throws IOException
Moves a directory to another directory.- Parameters:
src- the file to be moveddestDir- the destination filecreateDestDir- Iftruecreate the destination directory, otherwise iffalsethrow an IOException- Throws:
NullPointerException- if source or destination isnullorg.apache.commons.io.FileExistsException- if the directory exists in the destination directoryIOException- if source or destination is invalidIOException- if an IO error occurs moving the file- Since:
- 1.4
-
moveFile
public static void moveFile(File srcFile, File destFile) throws IOException
Moves a file.When the destination file is on another file system, do a "copy and delete".
- Parameters:
srcFile- the file to be moveddestFile- the destination file- Throws:
NullPointerException- if source or destination isnullorg.apache.commons.io.FileExistsException- if the destination file existsIOException- if source or destination is invalidIOException- if an IO error occurs moving the file- Since:
- 1.4
-
moveFileToDirectory
public static void moveFileToDirectory(File srcFile, File destDir, File dstFile, boolean createDestDir) throws IOException
- Throws:
IOException
-
moveFileToDirectory
public static void moveFileToDirectory(File srcFile, File destDir, boolean createDestDir) throws IOException
Moves a file to a directory.- Parameters:
srcFile- the file to be moveddestDir- the destination filecreateDestDir- Iftruecreate the destination directory, otherwise iffalsethrow an IOException- Throws:
NullPointerException- if source or destination isnullorg.apache.commons.io.FileExistsException- if the destination file existsIOException- if source or destination is invalidIOException- if an IO error occurs moving the file- Since:
- 1.4
-
moveToDirectory
public static void moveToDirectory(File src, File destDir, boolean createDestDir) throws IOException
Moves a file or directory to the destination directory.When the destination is on another file system, do a "copy and delete".
- Parameters:
src- the file or directory to be moveddestDir- the destination directorycreateDestDir- Iftruecreate the destination directory, otherwise iffalsethrow an IOException- Throws:
NullPointerException- if source or destination isnullorg.apache.commons.io.FileExistsException- if the directory or file exists in the destination directoryIOException- if source or destination is invalidIOException- if an IO error occurs moving the file- Since:
- 1.4
-
isSymlink
public static boolean isSymlink(File file) throws IOException
Determines whether the specified file is a Symbolic Link rather than an actual file.Will not return true if there is a Symbolic Link anywhere in the path, only if the specific file is.
Note: the current implementation always returns
falseif the system is detected as Windows usingFilenameUtils.isSystemWindows()- Parameters:
file- the file to check- Returns:
- true if the file is a Symbolic Link
- Throws:
IOException- if an IO error occurs while checking the file- Since:
- 2.0
-
-