Class FileUtils
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
Note that a specific charset should be specified whenever possible. Relying on the platform default means that the code is Locale-dependent. Only use the default if the files are known to always use the platform default.
SecurityException
are not documented in the Javadoc.
Origin of code: Excalibur, Alexandria, Commons-Utils
-
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final File[]
An empty array of typeFile
.static final long
The number of bytes in an exabyte.static final BigInteger
The number of bytes in an exabyte.static final long
The number of bytes in a gigabyte.static final BigInteger
The number of bytes in a gigabyte.static final long
The number of bytes in a kilobyte.static final BigInteger
The number of bytes in a kilobyte.static final long
The number of bytes in a megabyte.static final BigInteger
The number of bytes in a megabyte.static final long
The number of bytes in a petabyte.static final BigInteger
The number of bytes in a petabyte.static final long
The number of bytes in a terabyte.static final BigInteger
The number of bytes in a terabyte.static final BigInteger
The number of bytes in a yottabyte.static final BigInteger
The number of bytes in a zettabyte. -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionprivate static CopyOption[]
addCopyAttributes
(CopyOption... copyOptions) Copies the given array and adds StandardCopyOption.COPY_ATTRIBUTES.static String
byteCountToDisplaySize
(long size) Returns a human-readable version of the file size, where the input represents a specific number of bytes.static String
Returns a human-readable version of the file size, where the input represents a specific number of bytes.static Checksum
Computes the checksum of a file using the specified checksum object.static long
checksumCRC32
(File file) Computes the checksum of a file using the CRC32 checksum routine.static void
cleanDirectory
(File directory) Cleans a directory without deleting it.private static void
cleanDirectoryOnExit
(File directory) Cleans a directory without deleting it.static boolean
contentEquals
(File file1, File file2) Tests whether the contents of two files are equal.static boolean
contentEqualsIgnoreEOL
(File file1, File file2, String charsetName) Compares the contents of two files to determine if they are equal or not.static File[]
Converts a Collection containing java.io.File instanced into array representation.static void
copyDirectory
(File srcDir, File destDir) Copies a whole directory to a new location preserving the file dates.static void
copyDirectory
(File srcDir, File destDir, boolean preserveFileDate) Copies a whole directory to a new location.static void
copyDirectory
(File srcDir, File destDir, FileFilter filter) Copies a filtered directory to a new location preserving the file dates.static void
copyDirectory
(File srcDir, File destDir, FileFilter filter, boolean preserveFileDate) Copies a filtered directory to a new location.static void
copyDirectory
(File srcDir, File destDir, FileFilter fileFilter, boolean preserveFileDate, CopyOption... copyOptions) Copies a filtered directory to a new location.static void
copyDirectoryToDirectory
(File sourceDir, File destinationDir) Copies a directory to within another directory preserving the file dates.static void
Copies a file to a new location preserving the file date.static void
Copies an existing file to a new file location.static void
copyFile
(File srcFile, File destFile, boolean preserveFileDate, CopyOption... copyOptions) Copies a file to a new location.static void
copyFile
(File srcFile, File destFile, CopyOption... copyOptions) Copies a file to a new location.static long
copyFile
(File input, OutputStream output) Copies bytes from aFile
to anOutputStream
.static void
copyFileToDirectory
(File srcFile, File destDir) Copies a file to a directory preserving the file date.static void
copyFileToDirectory
(File sourceFile, File destinationDir, boolean preserveFileDate) Copies a file to a directory optionally preserving the file date.static void
copyInputStreamToFile
(InputStream source, File destination) static void
copyToDirectory
(File sourceFile, File destinationDir) Copies a file or directory to within another directory preserving the file dates.static void
copyToDirectory
(Iterable<File> sourceIterable, File destinationDir) Copies a files to a directory preserving each file's date.static void
copyToFile
(InputStream inputStream, File file) Copies bytes from anInputStream
source to aFile
destination.static void
copyURLToFile
(URL source, File destination) Copies bytes from the URLsource
to a filedestination
.static void
copyURLToFile
(URL source, File destination, int connectionTimeoutMillis, int readTimeoutMillis) Copies bytes from the URLsource
to a filedestination
.static File
createParentDirectories
(File file) Creates all parent directories for a File object.(package private) static String
Decodes the specified URL as per RFC 3986, i.e.static File
Deletes the given File but throws an IOException if it cannot, unlikeFile.delete()
which returns a boolean.static void
deleteDirectory
(File directory) Deletes a directory recursively.private static void
deleteDirectoryOnExit
(File directory) Schedules a directory recursively for deletion on JVM exit.static boolean
deleteQuietly
(File file) Deletes a file, never throwing an exception.static boolean
directoryContains
(File directory, File child) Determines whether theparent
directory contains thechild
element (a file or directory).private static void
doCopyDirectory
(File srcDir, File destDir, FileFilter fileFilter, List<String> exclusionList, boolean preserveDirDate, CopyOption... copyOptions) Internal copy directory method.static void
forceDelete
(File file) Deletes a file or directory.static void
forceDeleteOnExit
(File file) Schedules a file to be deleted when JVM exits.static void
forceMkdir
(File directory) Makes a directory, including any necessary but nonexistent parent directories.static void
forceMkdirParent
(File file) Makes any necessary but nonexistent parent directories for a given File.static File
Construct a file from the set of name elements.static File
Construct a file from the set of name elements.private static File
getParentFile
(File file) Gets the parent of the given file.static File
Returns aFile
representing the system temporary directory.static String
Returns the path to the system temporary directory.static File
Returns aFile
representing the user's home directory.static String
Returns the path to the user's home directory.static boolean
isDirectory
(File file, LinkOption... options) Tests whether the specifiedFile
is a directory or not.static boolean
isEmptyDirectory
(File directory) Tests whether the directory is empty.static boolean
isFileNewer
(File file, long timeMillis) Tests if the specifiedFile
is newer than the specified time reference.static boolean
isFileNewer
(File file, File reference) Tests if the specifiedFile
is newer than the referenceFile
.static boolean
isFileNewer
(File file, ChronoLocalDate chronoLocalDate) Tests if the specifiedFile
is newer than the specifiedChronoLocalDate
at the current time.static boolean
isFileNewer
(File file, ChronoLocalDate chronoLocalDate, LocalTime localTime) Tests if the specifiedFile
is newer than the specifiedChronoLocalDate
at the specified time.static boolean
isFileNewer
(File file, ChronoLocalDateTime<?> chronoLocalDateTime) Tests if the specifiedFile
is newer than the specifiedChronoLocalDateTime
at the system-default time zone.static boolean
isFileNewer
(File file, ChronoLocalDateTime<?> chronoLocalDateTime, ZoneId zoneId) Tests if the specifiedFile
is newer than the specifiedChronoLocalDateTime
at the specifiedZoneId
.static boolean
isFileNewer
(File file, ChronoZonedDateTime<?> chronoZonedDateTime) Tests if the specifiedFile
is newer than the specifiedChronoZonedDateTime
.static boolean
isFileNewer
(File file, Instant instant) Tests if the specifiedFile
is newer than the specifiedInstant
.static boolean
isFileNewer
(File file, Date date) Tests if the specifiedFile
is newer than the specifiedDate
.static boolean
isFileOlder
(File file, long timeMillis) Tests if the specifiedFile
is older than the specified time reference.static boolean
isFileOlder
(File file, File reference) Tests if the specifiedFile
is older than the referenceFile
.static boolean
isFileOlder
(File file, ChronoLocalDate chronoLocalDate) Tests if the specifiedFile
is older than the specifiedChronoLocalDate
at the current time.static boolean
isFileOlder
(File file, ChronoLocalDate chronoLocalDate, LocalTime localTime) Tests if the specifiedFile
is older than the specifiedChronoLocalDate
at the specifiedLocalTime
.static boolean
isFileOlder
(File file, ChronoLocalDateTime<?> chronoLocalDateTime) Tests if the specifiedFile
is older than the specifiedChronoLocalDateTime
at the system-default time zone.static boolean
isFileOlder
(File file, ChronoLocalDateTime<?> chronoLocalDateTime, ZoneId zoneId) Tests if the specifiedFile
is older than the specifiedChronoLocalDateTime
at the specifiedZoneId
.static boolean
isFileOlder
(File file, ChronoZonedDateTime<?> chronoZonedDateTime) Tests if the specifiedFile
is older than the specifiedChronoZonedDateTime
.static boolean
isFileOlder
(File file, Instant instant) Tests if the specifiedFile
is older than the specifiedInstant
.static boolean
isFileOlder
(File file, Date date) Tests if the specifiedFile
is older than the specifiedDate
.static boolean
isRegularFile
(File file, LinkOption... options) Tests whether the specifiedFile
is a regular file or not.static boolean
Tests whether the specified file is a symbolic link rather than an actual file.iterateFiles
(File directory, String[] extensions, boolean recursive) Iterates over the files in a given directory (and optionally its subdirectories) which match an array of extensions.iterateFiles
(File directory, IOFileFilter fileFilter, IOFileFilter dirFilter) Iterates over the files in given directory (and optionally its subdirectories).iterateFilesAndDirs
(File directory, IOFileFilter fileFilter, IOFileFilter dirFilter) Iterates over the files in given directory (and optionally its subdirectories).static long
lastModified
(File file) Returns the last modification time in milliseconds viaFiles.getLastModifiedTime(Path, LinkOption...)
.static long
lastModifiedUnchecked
(File file) Returns the last modification time in milliseconds viaFiles.getLastModifiedTime(Path, LinkOption...)
.static LineIterator
lineIterator
(File file) Returns an Iterator for the lines in aFile
using the default encoding for the VM.static LineIterator
lineIterator
(File file, String charsetName) Returns an Iterator for the lines in aFile
.private static AccumulatorPathVisitor
listAccumulate
(File directory, IOFileFilter fileFilter, IOFileFilter dirFilter) private static File[]
listFiles
(File directory, FileFilter fileFilter) Lists files in a directory, asserting that the supplied directory exists and is a directory.static Collection<File>
Finds files within a given directory (and optionally its subdirectories) which match an array of extensions.static Collection<File>
listFiles
(File directory, IOFileFilter fileFilter, IOFileFilter dirFilter) Finds files within a given directory (and optionally its subdirectories).static Collection<File>
listFilesAndDirs
(File directory, IOFileFilter fileFilter, IOFileFilter dirFilter) Finds files within a given directory (and optionally its subdirectories).private static File
CallsFile.mkdirs()
and throws an exception on failure.static void
moveDirectory
(File srcDir, File destDir) Moves a directory.static void
moveDirectoryToDirectory
(File src, File destDir, boolean createDestDir) Moves a directory to another directory.static void
Moves a file preserving attributes.static void
moveFile
(File srcFile, File destFile, CopyOption... copyOptions) Moves a file.static void
moveFileToDirectory
(File srcFile, File destDir, boolean createDestDir) Moves a file to a directory.static void
moveToDirectory
(File src, File destDir, boolean createDestDir) Moves a file or directory to the destination directory.static FileInputStream
openInputStream
(File file) Opens aFileInputStream
for the specified file, providing better error messages than simply callingnew FileInputStream(file)
.static FileOutputStream
openOutputStream
(File file) Opens aFileOutputStream
for the specified file, checking and creating the parent directory if it does not exist.static FileOutputStream
openOutputStream
(File file, boolean append) Opens aFileOutputStream
for 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 String
readFileToString
(File file) Deprecated.2.5 usereadFileToString(File, Charset)
instead (and specify the appropriate encoding)static String
readFileToString
(File file, String charsetName) Reads the contents of a file into a String.static String
readFileToString
(File file, Charset charsetName) Reads the contents of a file into a String.Deprecated.2.5 usereadLines(File, Charset)
instead (and specify the appropriate encoding)Reads the contents of a file line by line to a List of Strings.Reads the contents of a file line by line to a List of Strings.private static void
requireAbsent
(File file, String name) private static void
requireCanonicalPathsNotEquals
(File file1, File file2) Throws IllegalArgumentException if the given files' canonical representations are equal.private static void
requireCanWrite
(File file, String name) Throws anIllegalArgumentException
if the file is not writable.private static File
requireDirectory
(File directory, String name) Requires that the givenFile
is a directory.private static File
requireDirectoryExists
(File directory, String name) Requires that the givenFile
exists and is a directory.private static File
requireDirectoryIfExists
(File directory, String name) Requires that the givenFile
is a directory if it exists.private static void
requireEqualSizes
(File srcFile, File destFile, long srcLen, long dstLen) Requires that two file lengths are equal.private static File
requireExists
(File file, String fileParamName) Requires that the givenFile
exists and throws anIllegalArgumentException
if it doesn't.private static File
requireExistsChecked
(File file, String fileParamName) Requires that the givenFile
exists and throws anFileNotFoundException
if it doesn't.private static File
requireFile
(File file, String name) Requires that the givenFile
is a file.private static void
requireFileCopy
(File source, File destination) Requires parameter attributes for a file copy operation.private static File
requireFileIfExists
(File file, String name) Requires that the givenFile
is a file if it exists.private static void
setLastModified
(File file, long timeMillis) Sets the giventargetFile
's last modified date to the given value.private static void
setLastModified
(File sourceFile, File targetFile) Sets the giventargetFile
's last modified date to the value fromsourceFile
.static long
Returns the size of the specified file or directory.private static long
Gets the size of a file.static BigInteger
sizeOfAsBigInteger
(File file) Returns the size of the specified file or directory.private static BigInteger
sizeOfBig0
(File file) Returns the size of a file or directory.static long
sizeOfDirectory
(File directory) Counts the size of a directory recursively (sum of the length of all files).private static long
sizeOfDirectory0
(File directory) Gets the size of a directory.static BigInteger
sizeOfDirectoryAsBigInteger
(File directory) Counts the size of a directory recursively (sum of the length of all files).private static BigInteger
sizeOfDirectoryBig0
(File directory) Computes the size of a directory.streamFiles
(File directory, boolean recursive, String... extensions) Streams over the files in a given directory (and optionally its subdirectories) which match an array of extensions.static File
Converts from aURL
to aFile
.static File[]
Converts each of an array ofURL
to aFile
.private static int
toMaxDepth
(boolean recursive) Converts whether or not to recurse into a recursion max depth.private static String[]
toSuffixes
(String... extensions) Converts an array of file extensions to suffixes.static void
Implements the same behavior as the "touch" utility on Unix.static URL[]
Converts each of an array ofFile
to aURL
.private static void
validateMoveParameters
(File source, File destination) Validates the given arguments.static boolean
Waits for NFS to propagate a file creation, imposing a timeout.static void
write
(File file, CharSequence data) Deprecated.2.5 usewrite(File, CharSequence, Charset)
instead (and specify the appropriate encoding)static void
write
(File file, CharSequence data, boolean append) Deprecated.2.5 usewrite(File, CharSequence, Charset, boolean)
instead (and specify the appropriate encoding)static void
write
(File file, CharSequence data, String charsetName) Writes a CharSequence to a file creating the file if it does not exist.static void
write
(File file, CharSequence data, String charsetName, boolean append) Writes a CharSequence to a file creating the file if it does not exist.static void
write
(File file, CharSequence data, Charset charset) Writes a CharSequence to a file creating the file if it does not exist.static void
write
(File file, CharSequence data, Charset charset, boolean append) Writes a CharSequence to a file creating the file if it does not exist.static void
writeByteArrayToFile
(File file, byte[] data) Writes a byte array to a file creating the file if it does not exist.static void
writeByteArrayToFile
(File file, byte[] data, boolean append) Writes a byte array to a file creating the file if it does not exist.static void
writeByteArrayToFile
(File file, byte[] data, int off, int len) Writeslen
bytes from the specified byte array starting at offsetoff
to a file, creating the file if it does not exist.static void
writeByteArrayToFile
(File file, byte[] data, int off, int len, boolean append) Writeslen
bytes from the specified byte array starting at offsetoff
to a file, creating the file if it does not exist.static void
writeLines
(File file, String charsetName, Collection<?> lines) Writes thetoString()
value of each item in a collection to the specifiedFile
line by line.static void
writeLines
(File file, String charsetName, Collection<?> lines, boolean append) Writes thetoString()
value of each item in a collection to the specifiedFile
line by line, optionally appending.static void
writeLines
(File file, String charsetName, Collection<?> lines, String lineEnding) Writes thetoString()
value of each item in a collection to the specifiedFile
line by line.static void
writeLines
(File file, String charsetName, Collection<?> lines, String lineEnding, boolean append) Writes thetoString()
value of each item in a collection to the specifiedFile
line by line.static void
writeLines
(File file, Collection<?> lines) Writes thetoString()
value of each item in a collection to the specifiedFile
line by line.static void
writeLines
(File file, Collection<?> lines, boolean append) Writes thetoString()
value of each item in a collection to the specifiedFile
line by line.static void
writeLines
(File file, Collection<?> lines, String lineEnding) Writes thetoString()
value of each item in a collection to the specifiedFile
line by line.static void
writeLines
(File file, Collection<?> lines, String lineEnding, boolean append) Writes thetoString()
value of each item in a collection to the specifiedFile
line by line.static void
writeStringToFile
(File file, String data) Deprecated.2.5 usewriteStringToFile(File, String, Charset)
instead (and specify the appropriate encoding)static void
writeStringToFile
(File file, String data, boolean append) Deprecated.2.5 usewriteStringToFile(File, String, Charset, boolean)
instead (and specify the appropriate encoding)static void
writeStringToFile
(File file, String data, String charsetName) Writes a String to a file creating the file if it does not exist.static void
writeStringToFile
(File file, String data, String charsetName, boolean append) Writes a String to a file creating the file if it does not exist.static void
writeStringToFile
(File file, String data, Charset charset) Writes a String to a file creating the file if it does not exist.static void
writeStringToFile
(File file, String data, Charset charset, boolean append) Writes a String to a file creating the file if it does not exist.
-
Field Details
-
ONE_KB
public static final long ONE_KBThe number of bytes in a kilobyte.- See Also:
-
ONE_KB_BI
The number of bytes in a kilobyte.- Since:
- 2.4
-
ONE_MB
public static final long ONE_MBThe number of bytes in a megabyte.- See Also:
-
ONE_MB_BI
The number of bytes in a megabyte.- Since:
- 2.4
-
ONE_GB
public static final long ONE_GBThe number of bytes in a gigabyte.- See Also:
-
ONE_GB_BI
The number of bytes in a gigabyte.- Since:
- 2.4
-
ONE_TB
public static final long ONE_TBThe number of bytes in a terabyte.- See Also:
-
ONE_TB_BI
The number of bytes in a terabyte.- Since:
- 2.4
-
ONE_PB
public static final long ONE_PBThe number of bytes in a petabyte.- See Also:
-
ONE_PB_BI
The number of bytes in a petabyte.- Since:
- 2.4
-
ONE_EB
public static final long ONE_EBThe number of bytes in an exabyte.- See Also:
-
ONE_EB_BI
The number of bytes in an exabyte.- Since:
- 2.4
-
ONE_ZB
The number of bytes in a zettabyte. -
ONE_YB
The number of bytes in a yottabyte. -
EMPTY_FILE_ARRAY
An empty array of typeFile
.
-
-
Constructor Details
-
FileUtils
Deprecated.Will be private in 3.0.Instances should NOT be constructed in standard programming.
-
-
Method Details
-
addCopyAttributes
Copies the given array and adds StandardCopyOption.COPY_ATTRIBUTES.- Parameters:
copyOptions
- sorted copy options.- Returns:
- a new array.
-
byteCountToDisplaySize
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)
- Throws:
NullPointerException
- if the givenBigInteger
isnull
.- Since:
- 2.4
- See Also:
-
byteCountToDisplaySize
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:
-
checksum
Computes the checksum of a file using the specified checksum object. Multiple files may be checked using oneChecksum
instance if desired simply by reusing the same checksum object. For example:long checksum = FileUtils.checksum(file, new CRC32()).getValue();
- Parameters:
file
- the file to checksum, must not benull
checksum
- the checksum object to be used, must not benull
- Returns:
- the checksum specified, updated with the content of the file
- Throws:
NullPointerException
- if the givenFile
isnull
.NullPointerException
- if the givenChecksum
isnull
.IllegalArgumentException
- if the givenFile
does not exist or is not a file.IOException
- if an IO error occurs reading the file.- Since:
- 1.3
-
checksumCRC32
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 givenFile
isnull
.IllegalArgumentException
- if the givenFile
does not exist or is not a file.IOException
- if an IO error occurs reading the file.- Since:
- 1.3
-
cleanDirectory
Cleans a directory without deleting it.- Parameters:
directory
- directory to clean- Throws:
NullPointerException
- if the givenFile
isnull
.IllegalArgumentException
- if directory does not exist or is not a directory.IOException
- if an I/O error occurs.- See Also:
-
cleanDirectoryOnExit
Cleans a directory without deleting it.- Parameters:
directory
- directory to clean, must not benull
- Throws:
NullPointerException
- if the givenFile
isnull
.IllegalArgumentException
- if directory does not exist or is not a directory.IOException
- if an I/O error occurs.- See Also:
-
contentEquals
Tests whether the contents of two files are equal.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:
IllegalArgumentException
- when an input is not a file.IOException
- If an I/O error occurs.- See Also:
-
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 name of the requested charset. 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:
IllegalArgumentException
- when an input is not a file.IOException
- in case of an I/O error.UnsupportedCharsetException
- If the named charset is unavailable (unchecked exception).- Since:
- 2.2
- See Also:
-
convertFileCollectionToFileArray
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
-
copyDirectory
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, the methods throws IOException.- Parameters:
srcDir
- an existing directory to copy, must not benull
.destDir
- the new directory, must not benull
.- Throws:
NullPointerException
- if any of the givenFile
s arenull
.IllegalArgumentException
- if the source or destination is invalid.FileNotFoundException
- if the source does not exist.IOException
- if an error occurs or setting the last-modified time didn't succeeded.- 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
preserveFileDate
totrue
tries 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, the methods throws IOException.- Parameters:
srcDir
- an existing directory to copy, must not benull
.destDir
- the new directory, must not benull
.preserveFileDate
- true if the file date of the copy should be the same as the original.- Throws:
NullPointerException
- if any of the givenFile
s arenull
.IllegalArgumentException
- if the source or destination is invalid.FileNotFoundException
- if the source does not exist.IOException
- if an error occurs or setting the last-modified time didn't succeeded.- Since:
- 1.1
-
copyDirectory
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
Example: Copy directories onlyFile.setLastModified(long)
, however it is not guaranteed that those operations will succeed. If the modification operation fails, the methods throws IOException.// 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 benull
.destDir
- the new directory, must not benull
.filter
- the filter to apply, null means copy all directories and files should be the same as the original.- Throws:
NullPointerException
- if any of the givenFile
s arenull
.IllegalArgumentException
- if the source or destination is invalid.FileNotFoundException
- if the source does not exist.IOException
- if an error occurs or setting the last-modified time didn't succeeded.- 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
Example: Copy directories onlypreserveFileDate
totrue
tries 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, the methods throws IOException.// 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 benull
.destDir
- the new directory, must not benull
.filter
- the filter to apply, null means copy all directories and files.preserveFileDate
- true if the file date of the copy should be the same as the original.- Throws:
NullPointerException
- if any of the givenFile
s arenull
.IllegalArgumentException
- if the source or destination is invalid.FileNotFoundException
- if the source does not exist.IOException
- if an error occurs or setting the last-modified time didn't succeeded.- Since:
- 1.4
-
copyDirectory
public static void copyDirectory(File srcDir, File destDir, FileFilter fileFilter, boolean preserveFileDate, CopyOption... copyOptions) 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
Example: Copy directories onlypreserveFileDate
totrue
tries 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, the methods throws IOException.// 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 benull
destDir
- the new directory, must not benull
fileFilter
- 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 originalcopyOptions
- options specifying how the copy should be done, for exampleStandardCopyOption
.- Throws:
NullPointerException
- if any of the givenFile
s arenull
.IllegalArgumentException
- if the source or destination is invalid.FileNotFoundException
- if the source does not exist.IOException
- if an error occurs or setting the last-modified time didn't succeeded.- Since:
- 2.8.0
-
copyDirectoryToDirectory
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, the methods throws IOException.- Parameters:
sourceDir
- an existing directory to copy, must not benull
.destinationDir
- the directory to place the copy in, must not benull
.- Throws:
NullPointerException
- if any of the givenFile
s arenull
.IllegalArgumentException
- if the source or destination is invalid.FileNotFoundException
- if the source does not exist.IOException
- if an error occurs or setting the last-modified time didn't succeeded.- Since:
- 1.2
-
copyFile
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, the methods throws IOException.- Parameters:
srcFile
- an existing file to copy, must not benull
.destFile
- the new file, must not benull
.- Throws:
NullPointerException
- if any of the givenFile
s arenull
.IOException
- if source or destination is invalid.IOException
- if an error occurs or setting the last-modified time didn't succeeded.IOException
- if the output file length is not the same as the input file length after the copy completes.- See Also:
-
copyFile
public static void copyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException Copies an existing file to a new file 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
preserveFileDate
totrue
tries 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, the methods throws IOException.- Parameters:
srcFile
- an existing file to copy, must not benull
.destFile
- the new file, must not benull
.preserveFileDate
- true if the file date of the copy should be the same as the original.- Throws:
NullPointerException
- if any of the givenFile
s arenull
.IOException
- if source or destination is invalid.IOException
- if an error occurs or setting the last-modified time didn't succeeded.IOException
- if the output file length is not the same as the input file length after the copy completes- See Also:
-
copyFile
public static void copyFile(File srcFile, File destFile, boolean preserveFileDate, CopyOption... copyOptions) 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, you can overwrite it with
StandardCopyOption.REPLACE_EXISTING
.Note: Setting
preserveFileDate
totrue
tries 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, the methods throws IOException.- Parameters:
srcFile
- an existing file to copy, must not benull
.destFile
- the new file, must not benull
.preserveFileDate
- true if the file date of the copy should be the same as the original.copyOptions
- options specifying how the copy should be done, for exampleStandardCopyOption
..- Throws:
NullPointerException
- if any of the givenFile
s arenull
.FileNotFoundException
- if the source does not exist.IllegalArgumentException
- if source is not a file.IOException
- if the output file length is not the same as the input file length after the copy completes.IOException
- if an I/O error occurs, or setting the last-modified time didn't succeeded.- Since:
- 2.8.0
- See Also:
-
copyFile
public static void copyFile(File srcFile, File destFile, CopyOption... copyOptions) 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, you can overwrite it if you use
StandardCopyOption.REPLACE_EXISTING
.- Parameters:
srcFile
- an existing file to copy, must not benull
.destFile
- the new file, must not benull
.copyOptions
- options specifying how the copy should be done, for exampleStandardCopyOption
..- Throws:
NullPointerException
- if any of the givenFile
s arenull
.FileNotFoundException
- if the source does not exist.IllegalArgumentException
- if source is not a file.IOException
- if the output file length is not the same as the input file length after the copy completes.IOException
- if an I/O error occurs.- Since:
- 2.9.0
- See Also:
-
copyFile
Copies bytes from aFile
to anOutputStream
.This method buffers the input internally, so there is no need to use a
BufferedInputStream
.- Parameters:
input
- theFile
to read.output
- theOutputStream
to write.- Returns:
- the number of bytes copied
- Throws:
NullPointerException
- if the File isnull
.NullPointerException
- if the OutputStream isnull
.IOException
- if an I/O error occurs.- Since:
- 2.1
-
copyFileToDirectory
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, the methods throws IOException.- Parameters:
srcFile
- an existing file to copy, must not benull
.destDir
- the directory to place the copy in, must not benull
.- Throws:
NullPointerException
- if any of the givenFile
s arenull
.IllegalArgumentException
- if source or destination is invalid.IOException
- if an error occurs or setting the last-modified time didn't succeeded.- See Also:
-
copyFileToDirectory
public static void copyFileToDirectory(File sourceFile, File destinationDir, 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
preserveFileDate
totrue
tries 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, the methods throws IOException.- Parameters:
sourceFile
- an existing file to copy, must not benull
.destinationDir
- the directory to place the copy in, must not benull
.preserveFileDate
- true if the file date of the copy should be the same as the original.- Throws:
NullPointerException
- if any of the givenFile
s arenull
.IOException
- if an error occurs or setting the last-modified time didn't succeeded.IOException
- if the output file length is not the same as the input file length after the copy completes.- Since:
- 1.3
- See Also:
-
copyInputStreamToFile
Copies bytes from anInputStream
source
to a filedestination
. The directories up todestination
will be created if they don't already exist.destination
will be overwritten if it already exists.The
source
stream is closed.See
copyToFile(InputStream, File)
for a method that does not close the input stream.- Parameters:
source
- theInputStream
to copy bytes from, must not benull
, will be closeddestination
- the non-directoryFile
to write bytes to (possibly overwriting), must not benull
- Throws:
IOException
- ifdestination
is a directoryIOException
- ifdestination
cannot be writtenIOException
- ifdestination
needs creating but can't beIOException
- if an IO error occurs during copying- Since:
- 2.0
-
copyToDirectory
Copies a file or directory to within another directory preserving the file dates.This method copies the source file or directory, along 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, the methods throws IOException.- Parameters:
sourceFile
- an existing file or directory to copy, must not benull
.destinationDir
- the directory to place the copy in, must not benull
.- Throws:
NullPointerException
- if any of the givenFile
s arenull
.IllegalArgumentException
- if the source or destination is invalid.FileNotFoundException
- if the source does not exist.IOException
- if an error occurs or setting the last-modified time didn't succeeded.- Since:
- 2.6
- See Also:
-
copyToDirectory
public static void copyToDirectory(Iterable<File> sourceIterable, File destinationDir) throws IOException Copies a files to a directory preserving each file's date.This method copies the contents of the specified source files 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, the methods throws IOException.- Parameters:
sourceIterable
- a existing files to copy, must not benull
.destinationDir
- the directory to place the copy in, must not benull
.- Throws:
NullPointerException
- if any of the givenFile
s arenull
.IOException
- if source or destination is invalid.IOException
- if an error occurs or setting the last-modified time didn't succeeded.- Since:
- 2.6
- See Also:
-
copyToFile
Copies bytes from anInputStream
source to aFile
destination. The directories up todestination
will be created if they don't already exist.destination
will be overwritten if it already exists. Thesource
stream is left open, e.g. for use withZipInputStream
. SeecopyInputStreamToFile(InputStream, File)
for a method that closes the input stream.- Parameters:
inputStream
- theInputStream
to copy bytes from, must not benull
file
- the non-directoryFile
to write bytes to (possibly overwriting), must not benull
- Throws:
NullPointerException
- if the InputStream isnull
.NullPointerException
- if the File isnull
.IllegalArgumentException
- if the file object is a directory.IllegalArgumentException
- if the file is not writable.IOException
- if the directories could not be created.IOException
- if an IO error occurs during copying.- Since:
- 2.5
-
copyURLToFile
Copies bytes from the URLsource
to a filedestination
. The directories up todestination
will be created if they don't already exist.destination
will 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
- theURL
to copy bytes from, must not benull
destination
- the non-directoryFile
to write bytes to (possibly overwriting), must not benull
- Throws:
IOException
- ifsource
URL cannot be openedIOException
- ifdestination
is a directoryIOException
- ifdestination
cannot be writtenIOException
- ifdestination
needs creating but can't beIOException
- if an IO error occurs during copying
-
copyURLToFile
public static void copyURLToFile(URL source, File destination, int connectionTimeoutMillis, int readTimeoutMillis) throws IOException Copies bytes from the URLsource
to a filedestination
. The directories up todestination
will be created if they don't already exist.destination
will be overwritten if it already exists.- Parameters:
source
- theURL
to copy bytes from, must not benull
destination
- the non-directoryFile
to write bytes to (possibly overwriting), must not benull
connectionTimeoutMillis
- the number of milliseconds until this method will timeout if no connection could be established to thesource
readTimeoutMillis
- the number of milliseconds until this method will timeout if no data could be read from thesource
- Throws:
IOException
- ifsource
URL cannot be openedIOException
- ifdestination
is a directoryIOException
- ifdestination
cannot be writtenIOException
- ifdestination
needs creating but can't beIOException
- if an IO error occurs during copying- Since:
- 2.0
-
createParentDirectories
Creates all parent directories for a File object.- Parameters:
file
- the File that may need parents, may be null.- Returns:
- The parent directory, or
null
if the given file does not name a parent - Throws:
IOException
- if the directory was not created along with all its parent directories.IOException
- if the given file object is not null and not a directory.- Since:
- 2.9.0
-
decodeUrl
Decodes the specified URL as per RFC 3986, i.e. transforms percent-encoded octets to characters by decoding with the UTF-8 character set. This function is primarily intended for usage withURL
which unfortunately does not enforce proper URLs. As such, this method will leniently accept invalid characters or malformed percent-encoded octets and simply pass them literally through to the result string. Except for rare edge cases, this will make unencoded URLs pass through unaltered.- Parameters:
url
- The URL to decode, may benull
.- Returns:
- The decoded URL or
null
if the input wasnull
.
-
delete
Deletes the given File but throws an IOException if it cannot, unlikeFile.delete()
which returns a boolean.- Parameters:
file
- The file to delete.- Returns:
- the given file.
- Throws:
IOException
- if the file cannot be deleted.- Since:
- 2.9.0
- See Also:
-
deleteDirectory
Deletes a directory recursively.- Parameters:
directory
- directory to delete- Throws:
IOException
- in case deletion is unsuccessfulIllegalArgumentException
- ifdirectory
is not a directory
-
deleteDirectoryOnExit
Schedules a directory recursively for deletion on JVM exit.- Parameters:
directory
- directory to delete, must not benull
- Throws:
NullPointerException
- if the directory isnull
IOException
- in case deletion is unsuccessful
-
deleteQuietly
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:
true
if the file or directory was deleted, otherwisefalse
- Since:
- 1.4
-
directoryContains
Determines whether theparent
directory contains thechild
element (a file or directory).Files are normalized before comparison.
Edge cases:- A
directory
must not be null: if null, throw IllegalArgumentException - A
directory
must 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.NullPointerException
- if the givenFile
isnull
.IllegalArgumentException
- if the givenFile
does not exist or is not a directory.- Since:
- 2.2
- See Also:
- A
-
doCopyDirectory
private static void doCopyDirectory(File srcDir, File destDir, FileFilter fileFilter, List<String> exclusionList, boolean preserveDirDate, CopyOption... copyOptions) throws IOException Internal copy directory method.- Parameters:
srcDir
- the validated source directory, must not benull
.destDir
- the validated destination directory, must not benull
.fileFilter
- the filter to apply, null means copy all directories and files.exclusionList
- List of files and directories to exclude from the copy, may be null.preserveDirDate
- preserve the directories last modified dates.copyOptions
- options specifying how the copy should be done, seeStandardCopyOption
.- Throws:
IOException
- if the directory was not created along with all its parent directories.IOException
- if the given file object is not a directory.
-
forceDelete
Deletes a file or directory. For a directory, delete it and all sub-directories.The difference between File.delete() and this method are:
- The directory does not have to be empty.
- You get an exception when a file or directory cannot be deleted.
- Parameters:
file
- file or directory to delete, must not benull
.- Throws:
NullPointerException
- if the file isnull
.FileNotFoundException
- if the file was not found.IOException
- in case deletion is unsuccessful.
-
forceDeleteOnExit
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 isnull
.IOException
- in case deletion is unsuccessful.
-
forceMkdir
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 the file already exists but is not a directory) then an IOException is thrown.- Parameters:
directory
- directory to create, must not benull
.- Throws:
IOException
- if the directory was not created along with all its parent directories.IOException
- if the given file object is not a directory.SecurityException
- SeeFile.mkdirs()
.
-
forceMkdirParent
Makes any necessary but nonexistent parent directories for a given File. If the parent directory cannot be created then an IOException is thrown.- Parameters:
file
- file with parent to create, must not benull
.- Throws:
NullPointerException
- if the file isnull
.IOException
- if the parent directory cannot be created.- Since:
- 2.5
-
getFile
Construct a file from the set of name elements.- Parameters:
directory
- the parent directory.names
- the name elements.- Returns:
- the new file.
- Since:
- 2.1
-
getFile
Construct a file from the set of name elements.- Parameters:
names
- the name elements.- Returns:
- the file.
- Since:
- 2.1
-
getParentFile
Gets the parent of the given file. The given file may be bull and a file's parent may as well be null.- Parameters:
file
- The file to query.- Returns:
- The parent file or
null
.
-
getTempDirectory
Returns aFile
representing the system temporary directory.- Returns:
- the system temporary directory.
- Since:
- 2.0
-
getTempDirectoryPath
Returns the path to the system temporary directory.- Returns:
- the path to the system temporary directory.
- Since:
- 2.0
-
getUserDirectory
Returns aFile
representing the user's home directory.- Returns:
- the user's home directory.
- Since:
- 2.0
-
getUserDirectoryPath
Returns the path to the user's home directory.- Returns:
- the path to the user's home directory.
- Since:
- 2.0
-
isDirectory
Tests whether the specifiedFile
is a directory or not. Implemented as a null-safe delegate toFiles.isDirectory(Path path, LinkOption... options)
.- Parameters:
file
- the path to the file.options
- options indicating how symbolic links are handled- Returns:
true
if the file is a directory;false
if the path is null, the file does not exist, is not a directory, or it cannot be determined if the file is a directory or not.- Throws:
SecurityException
- In the case of the default provider, and a security manager is installed, thecheckRead
method is invoked to check read access to the directory.- Since:
- 2.9.0
-
isEmptyDirectory
Tests whether the directory is empty.- Parameters:
directory
- the directory to query.- Returns:
- whether the directory is empty.
- Throws:
IOException
- if an I/O error occurs.NotDirectoryException
- if the file could not otherwise be opened because it is not a directory (optional specific exception).- Since:
- 2.9.0
-
isFileNewer
Tests if the specifiedFile
is newer than the specifiedChronoLocalDate
at the current time.Note: The input date is assumed to be in the system default time-zone with the time part set to the current time. To use a non-default time-zone use the method
isFileNewer(file, chronoLocalDate.atTime(LocalTime.now(zoneId)), zoneId)
wherezoneId
is a validZoneId
.- Parameters:
file
- theFile
of which the modification date must be compared.chronoLocalDate
- the date reference.- Returns:
- true if the
File
exists and has been modified after the givenChronoLocalDate
at the current time. - Throws:
NullPointerException
- if the file or local date isnull
.- Since:
- 2.8.0
-
isFileNewer
Tests if the specifiedFile
is newer than the specifiedChronoLocalDate
at the specified time.Note: The input date and time are assumed to be in the system default time-zone. To use a non-default time-zone use the method
isFileNewer(file, chronoLocalDate.atTime(localTime), zoneId)
wherezoneId
is a validZoneId
.- Parameters:
file
- theFile
of which the modification date must be compared.chronoLocalDate
- the date reference.localTime
- the time reference.- Returns:
- true if the
File
exists and has been modified after the givenChronoLocalDate
at the given time. - Throws:
NullPointerException
- if the file, local date or zone ID isnull
.- Since:
- 2.8.0
-
isFileNewer
Tests if the specifiedFile
is newer than the specifiedChronoLocalDateTime
at the system-default time zone.Note: The input date and time is assumed to be in the system default time-zone. To use a non-default time-zone use the method
isFileNewer(file, chronoLocalDateTime, zoneId)
wherezoneId
is a validZoneId
.- Parameters:
file
- theFile
of which the modification date must be compared.chronoLocalDateTime
- the date reference.- Returns:
- true if the
File
exists and has been modified after the givenChronoLocalDateTime
at the system-default time zone. - Throws:
NullPointerException
- if the file or local date time isnull
.- Since:
- 2.8.0
-
isFileNewer
public static boolean isFileNewer(File file, ChronoLocalDateTime<?> chronoLocalDateTime, ZoneId zoneId) Tests if the specifiedFile
is newer than the specifiedChronoLocalDateTime
at the specifiedZoneId
.- Parameters:
file
- theFile
of which the modification date must be compared.chronoLocalDateTime
- the date reference.zoneId
- the time zone.- Returns:
- true if the
File
exists and has been modified after the givenChronoLocalDateTime
at the givenZoneId
. - Throws:
NullPointerException
- if the file, local date time or zone ID isnull
.- Since:
- 2.8.0
-
isFileNewer
Tests if the specifiedFile
is newer than the specifiedChronoZonedDateTime
.- Parameters:
file
- theFile
of which the modification date must be compared.chronoZonedDateTime
- the date reference.- Returns:
- true if the
File
exists and has been modified after the givenChronoZonedDateTime
. - Throws:
NullPointerException
- if the file or zoned date time isnull
.- Since:
- 2.8.0
-
isFileNewer
Tests if the specifiedFile
is newer than the specifiedDate
.- Parameters:
file
- theFile
of which the modification date must be compared.date
- the date reference.- Returns:
- true if the
File
exists and has been modified after the givenDate
. - Throws:
NullPointerException
- if the file or date isnull
.
-
isFileNewer
Tests if the specifiedFile
is newer than the referenceFile
.- Parameters:
file
- theFile
of which the modification date must be compared.reference
- theFile
of which the modification date is used.- Returns:
- true if the
File
exists and has been modified more recently than the referenceFile
. - Throws:
NullPointerException
- if the file or reference file isnull
.IllegalArgumentException
- if the reference file doesn't exist.
-
isFileNewer
Tests if the specifiedFile
is newer than the specifiedInstant
.- Parameters:
file
- theFile
of which the modification date must be compared.instant
- the date reference.- Returns:
- true if the
File
exists and has been modified after the givenInstant
. - Throws:
NullPointerException
- if the file or instant isnull
.- Since:
- 2.8.0
-
isFileNewer
Tests if the specifiedFile
is newer than the specified time reference.- Parameters:
file
- theFile
of which the modification date must be compared.timeMillis
- the time reference measured in milliseconds since the epoch (00:00:00 GMT, January 1, 1970).- Returns:
- true if the
File
exists and has been modified after the given time reference. - Throws:
NullPointerException
- if the file isnull
.
-
isFileOlder
Tests if the specifiedFile
is older than the specifiedChronoLocalDate
at the current time.Note: The input date is assumed to be in the system default time-zone with the time part set to the current time. To use a non-default time-zone use the method
isFileOlder(file, chronoLocalDate.atTime(LocalTime.now(zoneId)), zoneId)
wherezoneId
is a validZoneId
.- Parameters:
file
- theFile
of which the modification date must be compared.chronoLocalDate
- the date reference.- Returns:
- true if the
File
exists and has been modified before the givenChronoLocalDate
at the current time. - Throws:
NullPointerException
- if the file or local date isnull
.- Since:
- 2.8.0
- See Also:
-
isFileOlder
Tests if the specifiedFile
is older than the specifiedChronoLocalDate
at the specifiedLocalTime
.Note: The input date and time are assumed to be in the system default time-zone. To use a non-default time-zone use the method
isFileOlder(file, chronoLocalDate.atTime(localTime), zoneId)
wherezoneId
is a validZoneId
.- Parameters:
file
- theFile
of which the modification date must be compared.chronoLocalDate
- the date reference.localTime
- the time reference.- Returns:
- true if the
File
exists and has been modified before the givenChronoLocalDate
at the specified time. - Throws:
NullPointerException
- if the file, local date or local time isnull
.- Since:
- 2.8.0
- See Also:
-
isFileOlder
Tests if the specifiedFile
is older than the specifiedChronoLocalDateTime
at the system-default time zone.Note: The input date and time is assumed to be in the system default time-zone. To use a non-default time-zone use the method
isFileOlder(file, chronoLocalDateTime, zoneId)
wherezoneId
is a validZoneId
.- Parameters:
file
- theFile
of which the modification date must be compared.chronoLocalDateTime
- the date reference.- Returns:
- true if the
File
exists and has been modified before the givenChronoLocalDateTime
at the system-default time zone. - Throws:
NullPointerException
- if the file or local date time isnull
.- Since:
- 2.8.0
- See Also:
-
isFileOlder
public static boolean isFileOlder(File file, ChronoLocalDateTime<?> chronoLocalDateTime, ZoneId zoneId) Tests if the specifiedFile
is older than the specifiedChronoLocalDateTime
at the specifiedZoneId
.- Parameters:
file
- theFile
of which the modification date must be compared.chronoLocalDateTime
- the date reference.zoneId
- the time zone.- Returns:
- true if the
File
exists and has been modified before the givenChronoLocalDateTime
at the givenZoneId
. - Throws:
NullPointerException
- if the file, local date time or zone ID isnull
.- Since:
- 2.8.0
-
isFileOlder
Tests if the specifiedFile
is older than the specifiedChronoZonedDateTime
.- Parameters:
file
- theFile
of which the modification date must be compared.chronoZonedDateTime
- the date reference.- Returns:
- true if the
File
exists and has been modified before the givenChronoZonedDateTime
. - Throws:
NullPointerException
- if the file or zoned date time isnull
.- Since:
- 2.8.0
-
isFileOlder
Tests if the specifiedFile
is older than the specifiedDate
.- Parameters:
file
- theFile
of which the modification date must be compared.date
- the date reference.- Returns:
- true if the
File
exists and has been modified before the givenDate
. - Throws:
NullPointerException
- if the file or date isnull
.
-
isFileOlder
Tests if the specifiedFile
is older than the referenceFile
.- Parameters:
file
- theFile
of which the modification date must be compared.reference
- theFile
of which the modification date is used.- Returns:
- true if the
File
exists and has been modified before the referenceFile
. - Throws:
NullPointerException
- if the file or reference file isnull
.IllegalArgumentException
- if the reference file doesn't exist.
-
isFileOlder
Tests if the specifiedFile
is older than the specifiedInstant
.- Parameters:
file
- theFile
of which the modification date must be compared.instant
- the date reference.- Returns:
- true if the
File
exists and has been modified before the givenInstant
. - Throws:
NullPointerException
- if the file or instant isnull
.- Since:
- 2.8.0
-
isFileOlder
Tests if the specifiedFile
is older than the specified time reference.- Parameters:
file
- theFile
of which the modification date must be compared.timeMillis
- the time reference measured in milliseconds since the epoch (00:00:00 GMT, January 1, 1970).- Returns:
- true if the
File
exists and has been modified before the given time reference. - Throws:
NullPointerException
- if the file isnull
.
-
isRegularFile
Tests whether the specifiedFile
is a regular file or not. Implemented as a null-safe delegate toFiles.isRegularFile(Path path, LinkOption... options)
.- Parameters:
file
- the path to the file.options
- options indicating how symbolic links are handled- Returns:
true
if the file is a regular file;false
if the path is null, the file does not exist, is not a directory, or it cannot be determined if the file is a regular file or not.- Throws:
SecurityException
- In the case of the default provider, and a security manager is installed, thecheckRead
method is invoked to check read access to the directory.- Since:
- 2.9.0
-
isSymlink
Tests whether the specified file is a symbolic link rather than an actual file.This method delegates to
Files.isSymbolicLink(Path path)
- Parameters:
file
- the file to test.- Returns:
- true if the file is a symbolic link, see
Files.isSymbolicLink(Path path)
. - Since:
- 2.0
- See Also:
-
iterateFiles
public static Iterator<File> iterateFiles(File directory, IOFileFilter fileFilter, IOFileFilter dirFilter) Iterates over the files in given directory (and optionally its subdirectories).The resulting iterator MUST be consumed in its entirety in order to close its underlying stream.
All files found are filtered by an IOFileFilter.
- 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:
-
iterateFiles
Iterates over the files in a given directory (and optionally its subdirectories) which match an array of extensions.The resulting iterator MUST be consumed in its entirety in order to close its underlying stream.
- 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
-
iterateFilesAndDirs
public static Iterator<File> iterateFilesAndDirs(File directory, IOFileFilter fileFilter, IOFileFilter dirFilter) Iterates over the files in given directory (and optionally its subdirectories).The resulting iterator MUST be consumed in its entirety in order to close its underlying stream.
All files found are filtered by an IOFileFilter.
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:
-
lastModified
Returns the last modification time in milliseconds viaFiles.getLastModifiedTime(Path, LinkOption...)
.Use this method to avoid issues with
File.lastModified()
like JDK-8177809 whereFile.lastModified()
is losing milliseconds (always ends in 000). This bug exists in OpenJDK 8 and 9, and is fixed in 10.- Parameters:
file
- The File to query.- Returns:
- See
FileTime.toMillis()
. - Throws:
IOException
- if an I/O error occurs.- Since:
- 2.9.0
-
lastModifiedUnchecked
Returns the last modification time in milliseconds viaFiles.getLastModifiedTime(Path, LinkOption...)
.Use this method to avoid issues with
File.lastModified()
like JDK-8177809 whereFile.lastModified()
is losing milliseconds (always ends in 000). This bug exists in OpenJDK 8 and 9, and is fixed in 10.- Parameters:
file
- The File to query.- Returns:
- See
FileTime.toMillis()
. - Throws:
UncheckedIOException
- if an I/O error occurs.- Since:
- 2.9.0
-
lineIterator
Returns an Iterator for the lines in aFile
using 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:
NullPointerException
- if file isnull
.FileNotFoundException
- if the file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading.IOException
- if an I/O error occurs.- Since:
- 1.3
- See Also:
-
lineIterator
Returns an Iterator for the lines in aFile
.This method opens an
InputStream
for 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 benull
charsetName
- the name of the requested charset,null
means platform default- Returns:
- an Iterator of the lines in the file, never
null
- Throws:
NullPointerException
- if file isnull
.FileNotFoundException
- if the file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading.IOException
- if an I/O error occurs.- Since:
- 1.2
-
listAccumulate
private static AccumulatorPathVisitor listAccumulate(File directory, IOFileFilter fileFilter, IOFileFilter dirFilter) throws IOException - Throws:
IOException
-
listFiles
Lists files in a directory, asserting that the supplied directory exists and is a directory.- Parameters:
directory
- The directory to listfileFilter
- Optional file filter, may be null.- Returns:
- The files in the directory, never
null
. - Throws:
NullPointerException
- if directory isnull
.IllegalArgumentException
- if directory does not exist or is not a directory.IOException
- if an I/O error occurs.
-
listFiles
public static Collection<File> listFiles(File directory, IOFileFilter fileFilter, IOFileFilter dirFilter) Finds files within a given directory (and optionally its subdirectories). All files found are filtered by an IOFileFilter.If your search should recurse into subdirectories you can pass in an IOFileFilter for directories. You don't need to bind a DirectoryFileFilter (via logical AND) to this filter. This method does that for you.
An example: If you want to search through all directories called "temp" you pass in
FileFilterUtils.NameFileFilter("temp")
Another common usage of this method is find files in a directory tree but ignoring the directories generated CVS. You can simply pass in
FileFilterUtils.makeCVSAware(null)
.- Parameters:
directory
- the directory to search infileFilter
- filter to apply when finding files. Must not benull
, useTrueFileFilter.INSTANCE
to match all files in selected directories.dirFilter
- optional filter to apply when finding subdirectories. If this parameter isnull
, subdirectories will not be included in the search. UseTrueFileFilter.INSTANCE
to match all directories.- Returns:
- a collection of java.io.File with the matching files
- See Also:
-
listFiles
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:
- a collection of java.io.File with the matching files
-
listFilesAndDirs
public static Collection<File> listFilesAndDirs(File directory, IOFileFilter 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 starting directory and any subdirectories that match the directory filter.
- 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:
- a collection of java.io.File with the matching files
- Since:
- 2.2
- See Also:
-
mkdirs
CallsFile.mkdirs()
and throws an exception on failure.- Parameters:
directory
- the receiver formkdirs()
, may be null.- Returns:
- the given file, may be null.
- Throws:
IOException
- if the directory was not created along with all its parent directories.IOException
- if the given file object is not a directory.SecurityException
- SeeFile.mkdirs()
.- See Also:
-
moveDirectory
Moves a directory.When the destination directory is on another file system, do a "copy and delete".
- Parameters:
srcDir
- the directory to be moved.destDir
- the destination directory.- Throws:
NullPointerException
- if any of the givenFile
s arenull
.IllegalArgumentException
- if the source or destination is invalid.FileNotFoundException
- if the source does not exist.IOException
- if an error occurs or setting the last-modified time didn't succeeded.- 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 moved.destDir
- the destination file.createDestDir
- Iftrue
create the destination directory, otherwise iffalse
throw an IOException.- Throws:
NullPointerException
- if any of the givenFile
s arenull
.IllegalArgumentException
- if the source or destination is invalid.FileNotFoundException
- if the source does not exist.IOException
- if an error occurs or setting the last-modified time didn't succeeded.- Since:
- 1.4
-
moveFile
Moves a file preserving attributes.Shorthand for
moveFile(srcFile, destFile, StandardCopyOption.COPY_ATTRIBUTES)
.When the destination file is on another file system, do a "copy and delete".
- Parameters:
srcFile
- the file to be moved.destFile
- the destination file.- Throws:
NullPointerException
- if any of the givenFile
s arenull
.FileExistsException
- if the destination file exists.IOException
- if source or destination is invalid.IOException
- if an error occurs.- Since:
- 1.4
-
moveFile
public static void moveFile(File srcFile, File destFile, CopyOption... copyOptions) 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 moved.destFile
- the destination file.copyOptions
- Copy options.- Throws:
NullPointerException
- if any of the givenFile
s arenull
.FileExistsException
- if the destination file exists.IOException
- if source or destination is invalid.IOException
- if an error occurs or setting the last-modified time didn't succeeded.- Since:
- 2.9.0
-
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 moved.destDir
- the destination file.createDestDir
- Iftrue
create the destination directory, otherwise iffalse
throw an IOException.- Throws:
NullPointerException
- if any of the givenFile
s arenull
.FileExistsException
- if the destination file exists.IOException
- if source or destination is invalid.IOException
- if an error occurs or setting the last-modified time didn't succeeded.- 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 moved.destDir
- the destination directory.createDestDir
- Iftrue
create the destination directory, otherwise iffalse
throw an IOException.- Throws:
NullPointerException
- if any of the givenFile
s arenull
.FileExistsException
- if the directory or file exists in the destination directory.IOException
- if source or destination is invalid.IOException
- if an error occurs or setting the last-modified time didn't succeeded.- Since:
- 1.4
-
openInputStream
Opens aFileInputStream
for 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
FileInputStream
for the specified file - Throws:
NullPointerException
- if file isnull
.FileNotFoundException
- if the file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading.IOException
- See FileNotFoundException above, FileNotFoundException is a subclass of IOException.- Since:
- 1.3
-
openOutputStream
Opens aFileOutputStream
for 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
FileOutputStream
for the specified file - Throws:
NullPointerException
- if the file object isnull
.IllegalArgumentException
- if the file object is a directoryIllegalArgumentException
- if the file is not writable.IOException
- if the directories could not be created.- Since:
- 1.3
-
openOutputStream
Opens aFileOutputStream
for 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
append
- iftrue
, then bytes will be added to the end of the file rather than overwriting- Returns:
- a new
FileOutputStream
for the specified file - Throws:
NullPointerException
- if the file object isnull
.IllegalArgumentException
- if the file object is a directoryIllegalArgumentException
- if the file is not writable.IOException
- if the directories could not be created.- Since:
- 2.1
-
readFileToByteArray
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:
NullPointerException
- if file isnull
.FileNotFoundException
- if the file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading.IOException
- if an I/O error occurs.- Since:
- 1.1
-
readFileToString
Deprecated.2.5 usereadFileToString(File, Charset)
instead (and specify the appropriate encoding)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:
NullPointerException
- if file isnull
.FileNotFoundException
- if the file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading.IOException
- if an I/O error occurs.- Since:
- 1.3.1
-
readFileToString
Reads the contents of a file into a String. The file is always closed.- Parameters:
file
- the file to read, must not benull
charsetName
- the name of the requested charset,null
means platform default- Returns:
- the file contents, never
null
- Throws:
NullPointerException
- if file isnull
.FileNotFoundException
- if the file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading.IOException
- if an I/O error occurs.- Since:
- 2.3
-
readFileToString
Reads the contents of a file into a String. The file is always closed.- Parameters:
file
- the file to read, must not benull
charsetName
- the name of the requested charset,null
means platform default- Returns:
- the file contents, never
null
- Throws:
NullPointerException
- if file isnull
.FileNotFoundException
- if the file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading.IOException
- if an I/O error occurs.UnsupportedCharsetException
- thrown instead of.UnsupportedEncodingException
in version 2.2 if the named charset is unavailable.- Since:
- 2.3
-
readLines
Deprecated.2.5 usereadLines(File, Charset)
instead (and specify the appropriate encoding)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:
NullPointerException
- if file isnull
.FileNotFoundException
- if the file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading.IOException
- if an I/O error occurs.- Since:
- 1.3
-
readLines
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 benull
charset
- the charset to use,null
means platform default- Returns:
- the list of Strings representing each line in the file, never
null
- Throws:
NullPointerException
- if file isnull
.FileNotFoundException
- if the file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading.IOException
- if an I/O error occurs.- Since:
- 2.3
-
readLines
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 benull
charsetName
- the name of the requested charset,null
means platform default- Returns:
- the list of Strings representing each line in the file, never
null
- Throws:
NullPointerException
- if file isnull
.FileNotFoundException
- if the file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading.IOException
- if an I/O error occurs.UnsupportedCharsetException
- thrown instead of.UnsupportedEncodingException
in version 2.2 if the named charset is unavailable.- Since:
- 1.1
-
requireAbsent
- Throws:
FileExistsException
-
requireCanonicalPathsNotEquals
Throws IllegalArgumentException if the given files' canonical representations are equal.- Parameters:
file1
- The first file to compare.file2
- The second file to compare.- Throws:
IllegalArgumentException
- if the given files' canonical representations are equal.IOException
-
requireCanWrite
Throws anIllegalArgumentException
if the file is not writable. This provides a more precise exception message than a plain access denied.- Parameters:
file
- The file to test.name
- The parameter name to use in the exception message.- Throws:
NullPointerException
- if the givenFile
isnull
.IllegalArgumentException
- if the file is not writable.
-
requireDirectory
Requires that the givenFile
is a directory.- Parameters:
directory
- TheFile
to check.name
- The parameter name to use in the exception message in case of null input or if the file is not a directory.- Returns:
- the given directory.
- Throws:
NullPointerException
- if the givenFile
isnull
.IllegalArgumentException
- if the givenFile
does not exist or is not a directory.
-
requireDirectoryExists
Requires that the givenFile
exists and is a directory.- Parameters:
directory
- TheFile
to check.name
- The parameter name to use in the exception message in case of null input.- Returns:
- the given directory.
- Throws:
NullPointerException
- if the givenFile
isnull
.IllegalArgumentException
- if the givenFile
does not exist or is not a directory.
-
requireDirectoryIfExists
Requires that the givenFile
is a directory if it exists.- Parameters:
directory
- TheFile
to check.name
- The parameter name to use in the exception message in case of null input.- Returns:
- the given directory.
- Throws:
NullPointerException
- if the givenFile
isnull
.IllegalArgumentException
- if the givenFile
exists but is not a directory.
-
requireEqualSizes
private static void requireEqualSizes(File srcFile, File destFile, long srcLen, long dstLen) throws IOException Requires that two file lengths are equal.- Parameters:
srcFile
- Source file.destFile
- Destination file.srcLen
- Source file length.dstLen
- Destination file length- Throws:
IOException
- Thrown when the given sizes are not equal.
-
requireExists
Requires that the givenFile
exists and throws anIllegalArgumentException
if it doesn't.- Parameters:
file
- TheFile
to check.fileParamName
- The parameter name to use in the exception message in case ofnull
input.- Returns:
- the given file.
- Throws:
NullPointerException
- if the givenFile
isnull
.IllegalArgumentException
- if the givenFile
does not exist.
-
requireExistsChecked
private static File requireExistsChecked(File file, String fileParamName) throws FileNotFoundException Requires that the givenFile
exists and throws anFileNotFoundException
if it doesn't.- Parameters:
file
- TheFile
to check.fileParamName
- The parameter name to use in the exception message in case ofnull
input.- Returns:
- the given file.
- Throws:
NullPointerException
- if the givenFile
isnull
.FileNotFoundException
- if the givenFile
does not exist.
-
requireFile
Requires that the givenFile
is a file.- Parameters:
file
- TheFile
to check.name
- The parameter name to use in the exception message.- Returns:
- the given file.
- Throws:
NullPointerException
- if the givenFile
isnull
.IllegalArgumentException
- if the givenFile
does not exist or is not a directory.
-
requireFileCopy
Requires parameter attributes for a file copy operation.- Parameters:
source
- the source filedestination
- the destination- Throws:
NullPointerException
- if any of the givenFile
s arenull
.FileNotFoundException
- if the source does not exist.
-
requireFileIfExists
Requires that the givenFile
is a file if it exists.- Parameters:
file
- TheFile
to check.name
- The parameter name to use in the exception message in case of null input.- Returns:
- the given directory.
- Throws:
NullPointerException
- if the givenFile
isnull
.IllegalArgumentException
- if the givenFile
does exists but is not a directory.
-
setLastModified
Sets the giventargetFile
's last modified date to the value fromsourceFile
.- Parameters:
sourceFile
- The source file to query.targetFile
- The target file to set.- Throws:
NullPointerException
- if sourceFile isnull
.NullPointerException
- if targetFile isnull
.IOException
- if setting the last-modified time failed.
-
setLastModified
Sets the giventargetFile
's last modified date to the given value.- Parameters:
file
- The source file to query.timeMillis
- The new last-modified time, measured in milliseconds since the epoch 01-01-1970 GMT.- Throws:
NullPointerException
- if file isnull
.IOException
- if setting the last-modified time failed.
-
sizeOf
Returns the size of the specified file or directory. If the providedFile
is 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.Note that overflow is not detected, and the return value may be negative if overflow occurs. See
sizeOfAsBigInteger(File)
for an alternative method that does not overflow.- 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 isnull
.IllegalArgumentException
- if the file does not exist.- Since:
- 2.0
-
sizeOf0
Gets the size of a file.- Parameters:
file
- the file to check.- Returns:
- the size of the file.
- Throws:
NullPointerException
- if the file isnull
.
-
sizeOfAsBigInteger
Returns the size of the specified file or directory. If the providedFile
is 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 isnull
.IllegalArgumentException
- if the file does not exist.- Since:
- 2.4
-
sizeOfBig0
Returns the size of a file or directory.- Parameters:
file
- The file or directory.- Returns:
- the size
-
sizeOfDirectory
Counts the size of a directory recursively (sum of the length of all files).Note that overflow is not detected, and the return value may be negative if overflow occurs. See
sizeOfDirectoryAsBigInteger(File)
for an alternative method that does not overflow.- 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
.
-
sizeOfDirectory0
Gets the size of a directory.- Parameters:
directory
- the directory to check- Returns:
- the size
- Throws:
NullPointerException
- if the directory isnull
.
-
sizeOfDirectoryAsBigInteger
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
-
sizeOfDirectoryBig0
Computes the size of a directory.- Parameters:
directory
- The directory.- Returns:
- the size.
-
streamFiles
public static Stream<File> streamFiles(File directory, boolean recursive, String... extensions) throws IOException Streams over the files in a given directory (and optionally its subdirectories) which match an array of extensions.- Parameters:
directory
- the directory to search inrecursive
- if true all subdirectories are searched as wellextensions
- an array of extensions, ex. {"java","xml"}. If this parameter isnull
, all files are returned.- Returns:
- an iterator of java.io.File with the matching files
- Throws:
IOException
- if an I/O error is thrown when accessing the starting file.- Since:
- 2.9.0
-
toFile
Converts from aURL
to aFile
.From version 1.1 this method will decode the URL. Syntax such as
file:///my%20docs/file.txt
will 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,null
returnsnull
- Returns:
- the equivalent
File
object, ornull
if the URL's protocol is notfile
-
toFiles
Converts each of an array ofURL
to 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 containsnull
at the same index.This method will decode the URL. Syntax such as
file:///my%20docs/file.txt
will be correctly decoded to/my docs/file.txt
.- Parameters:
urls
- the file URLs to convert,null
returns empty array- Returns:
- a non-
null
array of Files matching the input, with anull
item if there was anull
at 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
-
toList
-
toMaxDepth
private static int toMaxDepth(boolean recursive) Converts whether or not to recurse into a recursion max depth.- Parameters:
recursive
- whether or not to recurse- Returns:
- the recursion depth
-
toSuffixes
Converts an array of file extensions to suffixes.- Parameters:
extensions
- an array of extensions. Format: {"java", "xml"}- Returns:
- an array of suffixes. Format: {".java", ".xml"}
- Throws:
NullPointerException
- if the parameter is null
-
touch
Implements the same behavior 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.IOException
- if setting the last-modified time failed.
-
toURLs
Converts each of an array ofFile
to 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
-
validateMoveParameters
private static void validateMoveParameters(File source, File destination) throws FileNotFoundException Validates the given arguments.- Throws
NullPointerException
ifsource
is null - Throws
NullPointerException
ifdestination
is null - Throws
FileNotFoundException
ifsource
does not exist
- Parameters:
source
- the file or directory to be moveddestination
- the destination file or directory- Throws:
FileNotFoundException
- ifsource
file does not exist
- Throws
-
waitFor
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 benull
seconds
- the maximum time in seconds to wait- Returns:
- true if file exists
- Throws:
NullPointerException
- if the file isnull
-
write
Deprecated.2.5 usewrite(File, CharSequence, Charset)
instead (and specify the appropriate encoding)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
@Deprecated public static void write(File file, CharSequence data, boolean append) throws IOException Deprecated.2.5 usewrite(File, CharSequence, Charset, boolean)
instead (and specify the appropriate encoding)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
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 filecharset
- the name of the requested charset,null
means platform default- Throws:
IOException
- in case of an I/O error- Since:
- 2.3
-
write
public static void write(File file, CharSequence data, Charset charset, 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 filecharset
- the charset to use,null
means 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
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 filecharsetName
- the name of the requested charset,null
means 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, String charsetName, 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 filecharsetName
- the name of the requested charset,null
means 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 of.UnsupportedEncodingException
in version 2.2 if the encoding is not supported by the VM- Since:
- 2.1
-
writeByteArrayToFile
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
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:
- 2.1
-
writeByteArrayToFile
public static void writeByteArrayToFile(File file, byte[] data, int off, int len) throws IOException Writeslen
bytes from the specified byte array starting at offsetoff
to a file, creating the file if it does not exist.- Parameters:
file
- the file to write todata
- the content to write to the fileoff
- the start offset in the datalen
- the number of bytes to write- Throws:
IOException
- in case of an I/O error- Since:
- 2.5
-
writeByteArrayToFile
public static void writeByteArrayToFile(File file, byte[] data, int off, int len, boolean append) throws IOException Writeslen
bytes from the specified byte array starting at offsetoff
to a file, creating the file if it does not exist.- Parameters:
file
- the file to write todata
- the content to write to the fileoff
- the start offset in the datalen
- the number of bytes to writeappend
- 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:
- 2.5
-
writeLines
Writes thetoString()
value of each item in a collection to the specifiedFile
line 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,null
entries produce blank lines- Throws:
IOException
- in case of an I/O error- Since:
- 1.3
-
writeLines
Writes thetoString()
value of each item in a collection to the specifiedFile
line 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,null
entries 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
Writes thetoString()
value of each item in a collection to the specifiedFile
line 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,null
entries produce blank lineslineEnding
- the line separator to use,null
is 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 specifiedFile
line 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,null
entries produce blank lineslineEnding
- the line separator to use,null
is 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
-
writeLines
public static void writeLines(File file, String charsetName, Collection<?> lines) throws IOException Writes thetoString()
value of each item in a collection to the specifiedFile
line 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 tocharsetName
- the name of the requested charset,null
means platform defaultlines
- the lines to write,null
entries 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 charsetName, Collection<?> lines, boolean append) throws IOException Writes thetoString()
value of each item in a collection to the specifiedFile
line by line, optionally appending. The specified character encoding and the default line ending will be used.- Parameters:
file
- the file to write tocharsetName
- the name of the requested charset,null
means platform defaultlines
- the lines to write,null
entries 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, String charsetName, Collection<?> lines, String lineEnding) throws IOException Writes thetoString()
value of each item in a collection to the specifiedFile
line 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 tocharsetName
- the name of the requested charset,null
means platform defaultlines
- the lines to write,null
entries produce blank lineslineEnding
- the line separator to use,null
is 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 charsetName, Collection<?> lines, String lineEnding, boolean append) throws IOException Writes thetoString()
value of each item in a collection to the specifiedFile
line by line. The specified character encoding and the line ending will be used.- Parameters:
file
- the file to write tocharsetName
- the name of the requested charset,null
means platform defaultlines
- the lines to write,null
entries produce blank lineslineEnding
- the line separator to use,null
is 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
-
writeStringToFile
Deprecated.2.5 usewriteStringToFile(File, String, Charset)
instead (and specify the appropriate encoding)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
@Deprecated public static void writeStringToFile(File file, String data, boolean append) throws IOException Deprecated.2.5 usewriteStringToFile(File, String, Charset, boolean)
instead (and specify the appropriate encoding)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
-
writeStringToFile
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 filecharset
- the charset to use,null
means 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, Charset charset, 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 filecharset
- the charset to use,null
means 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
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 filecharsetName
- the name of the requested charset,null
means 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, String charsetName, 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 filecharsetName
- the name of the requested charset,null
means 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 of.UnsupportedEncodingException
in version 2.2 if the encoding is not supported by the VM- Since:
- 2.1
-