Class FileUtils
- java.lang.Object
-
- org.apache.commons.io.FileUtils
-
public class FileUtils extends java.lang.ObjectGeneral file manipulation utilities.Facilities are provided in the following areas:
- writing to a file
- reading from a file
- make a directory including parent directories
- copying files and directories
- deleting files and directories
- converting to and from a URL
- listing files and directories by filter and extension
- comparing file content
- file last changed date
- calculating a checksum
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.
SecurityExceptionare not documented in the Javadoc.Origin of code: Excalibur, Alexandria, Commons-Utils
-
-
Field Summary
Fields Modifier and Type Field Description static java.io.File[]EMPTY_FILE_ARRAYAn empty array of typeFile.static longONE_EBThe number of bytes in an exabyte.static java.math.BigIntegerONE_EB_BIThe number of bytes in an exabyte.static longONE_GBThe number of bytes in a gigabyte.static java.math.BigIntegerONE_GB_BIThe number of bytes in a gigabyte.static longONE_KBThe number of bytes in a kilobyte.static java.math.BigIntegerONE_KB_BIThe number of bytes in a kilobyte.static longONE_MBThe number of bytes in a megabyte.static java.math.BigIntegerONE_MB_BIThe number of bytes in a megabyte.static longONE_PBThe number of bytes in a petabyte.static java.math.BigIntegerONE_PB_BIThe number of bytes in a petabyte.static longONE_TBThe number of bytes in a terabyte.static java.math.BigIntegerONE_TB_BIThe number of bytes in a terabyte.static java.math.BigIntegerONE_YBThe number of bytes in a yottabyte.static java.math.BigIntegerONE_ZBThe number of bytes in a zettabyte.
-
Constructor Summary
Constructors Constructor Description FileUtils()Deprecated.Will be private in 3.0.
-
Method Summary
All Methods Static Methods Concrete Methods Deprecated Methods Modifier and Type Method Description static java.lang.StringbyteCountToDisplaySize(long size)Returns a human-readable version of the file size, where the input represents a specific number of bytes.static java.lang.StringbyteCountToDisplaySize(java.math.BigInteger size)Returns a human-readable version of the file size, where the input represents a specific number of bytes.static java.util.zip.Checksumchecksum(java.io.File file, java.util.zip.Checksum checksum)Computes the checksum of a file using the specified checksum object.static longchecksumCRC32(java.io.File file)Computes the checksum of a file using the CRC32 checksum routine.static voidcleanDirectory(java.io.File directory)Cleans a directory without deleting it.static booleancontentEquals(java.io.File file1, java.io.File file2)Tests whether the contents of two files are equal.static booleancontentEqualsIgnoreEOL(java.io.File file1, java.io.File file2, java.lang.String charsetName)Compares the contents of two files to determine if they are equal or not.static java.io.File[]convertFileCollectionToFileArray(java.util.Collection<java.io.File> files)Converts a Collection containing java.io.File instanced into array representation.static voidcopyDirectory(java.io.File srcDir, java.io.File destDir)Copies a whole directory to a new location preserving the file dates.static voidcopyDirectory(java.io.File srcDir, java.io.File destDir, boolean preserveFileDate)Copies a whole directory to a new location.static voidcopyDirectory(java.io.File srcDir, java.io.File destDir, java.io.FileFilter filter)Copies a filtered directory to a new location preserving the file dates.static voidcopyDirectory(java.io.File srcDir, java.io.File destDir, java.io.FileFilter filter, boolean preserveFileDate)Copies a filtered directory to a new location.static voidcopyDirectory(java.io.File srcDir, java.io.File destDir, java.io.FileFilter fileFilter, boolean preserveFileDate, java.nio.file.CopyOption... copyOptions)Copies a filtered directory to a new location.static voidcopyDirectoryToDirectory(java.io.File sourceDir, java.io.File destinationDir)Copies a directory to within another directory preserving the file dates.static voidcopyFile(java.io.File srcFile, java.io.File destFile)Copies a file to a new location preserving the file date.static voidcopyFile(java.io.File srcFile, java.io.File destFile, boolean preserveFileDate)Copies an existing file to a new file location.static voidcopyFile(java.io.File srcFile, java.io.File destFile, boolean preserveFileDate, java.nio.file.CopyOption... copyOptions)Copies a file to a new location.static voidcopyFile(java.io.File srcFile, java.io.File destFile, java.nio.file.CopyOption... copyOptions)Copies a file to a new location.static longcopyFile(java.io.File input, java.io.OutputStream output)Copies bytes from aFileto anOutputStream.static voidcopyFileToDirectory(java.io.File srcFile, java.io.File destDir)Copies a file to a directory preserving the file date.static voidcopyFileToDirectory(java.io.File sourceFile, java.io.File destinationDir, boolean preserveFileDate)Copies a file to a directory optionally preserving the file date.static voidcopyInputStreamToFile(java.io.InputStream source, java.io.File destination)Copies bytes from anInputStreamsourceto a filedestination.static voidcopyToDirectory(java.io.File sourceFile, java.io.File destinationDir)Copies a file or directory to within another directory preserving the file dates.static voidcopyToDirectory(java.lang.Iterable<java.io.File> sourceIterable, java.io.File destinationDir)Copies a files to a directory preserving each file's date.static voidcopyToFile(java.io.InputStream inputStream, java.io.File file)Copies bytes from anInputStreamsource to aFiledestination.static voidcopyURLToFile(java.net.URL source, java.io.File destination)Copies bytes from the URLsourceto a filedestination.static voidcopyURLToFile(java.net.URL source, java.io.File destination, int connectionTimeoutMillis, int readTimeoutMillis)Copies bytes from the URLsourceto a filedestination.static java.io.FilecreateParentDirectories(java.io.File file)Creates all parent directories for a File object.static java.io.Filedelete(java.io.File file)Deletes the given File but throws an IOException if it cannot, unlikeFile.delete()which returns a boolean.static voiddeleteDirectory(java.io.File directory)Deletes a directory recursively.static booleandeleteQuietly(java.io.File file)Deletes a file, never throwing an exception.static booleandirectoryContains(java.io.File directory, java.io.File child)Determines whether theparentdirectory contains thechildelement (a file or directory).static voidforceDelete(java.io.File file)Deletes a file or directory.static voidforceDeleteOnExit(java.io.File file)Schedules a file to be deleted when JVM exits.static voidforceMkdir(java.io.File directory)Makes a directory, including any necessary but nonexistent parent directories.static voidforceMkdirParent(java.io.File file)Makes any necessary but nonexistent parent directories for a given File.static java.io.FilegetFile(java.io.File directory, java.lang.String... names)Construct a file from the set of name elements.static java.io.FilegetFile(java.lang.String... names)Construct a file from the set of name elements.static java.io.FilegetTempDirectory()Returns aFilerepresenting the system temporary directory.static java.lang.StringgetTempDirectoryPath()Returns the path to the system temporary directory.static java.io.FilegetUserDirectory()Returns aFilerepresenting the user's home directory.static java.lang.StringgetUserDirectoryPath()Returns the path to the user's home directory.static booleanisDirectory(java.io.File file, java.nio.file.LinkOption... options)Tests whether the specifiedFileis a directory or not.static booleanisEmptyDirectory(java.io.File directory)Tests whether the directory is empty.static booleanisFileNewer(java.io.File file, long timeMillis)Tests if the specifiedFileis newer than the specified time reference.static booleanisFileNewer(java.io.File file, java.io.File reference)Tests if the specifiedFileis newer than the referenceFile.static booleanisFileNewer(java.io.File file, java.time.chrono.ChronoLocalDate chronoLocalDate)Tests if the specifiedFileis newer than the specifiedChronoLocalDateat the current time.static booleanisFileNewer(java.io.File file, java.time.chrono.ChronoLocalDate chronoLocalDate, java.time.LocalTime localTime)Tests if the specifiedFileis newer than the specifiedChronoLocalDateat the specified time.static booleanisFileNewer(java.io.File file, java.time.chrono.ChronoLocalDateTime<?> chronoLocalDateTime)Tests if the specifiedFileis newer than the specifiedChronoLocalDateTimeat the system-default time zone.static booleanisFileNewer(java.io.File file, java.time.chrono.ChronoLocalDateTime<?> chronoLocalDateTime, java.time.ZoneId zoneId)Tests if the specifiedFileis newer than the specifiedChronoLocalDateTimeat the specifiedZoneId.static booleanisFileNewer(java.io.File file, java.time.chrono.ChronoZonedDateTime<?> chronoZonedDateTime)Tests if the specifiedFileis newer than the specifiedChronoZonedDateTime.static booleanisFileNewer(java.io.File file, java.time.Instant instant)Tests if the specifiedFileis newer than the specifiedInstant.static booleanisFileNewer(java.io.File file, java.util.Date date)Tests if the specifiedFileis newer than the specifiedDate.static booleanisFileOlder(java.io.File file, long timeMillis)Tests if the specifiedFileis older than the specified time reference.static booleanisFileOlder(java.io.File file, java.io.File reference)Tests if the specifiedFileis older than the referenceFile.static booleanisFileOlder(java.io.File file, java.time.chrono.ChronoLocalDate chronoLocalDate)Tests if the specifiedFileis older than the specifiedChronoLocalDateat the current time.static booleanisFileOlder(java.io.File file, java.time.chrono.ChronoLocalDate chronoLocalDate, java.time.LocalTime localTime)Tests if the specifiedFileis older than the specifiedChronoLocalDateat the specifiedLocalTime.static booleanisFileOlder(java.io.File file, java.time.chrono.ChronoLocalDateTime<?> chronoLocalDateTime)Tests if the specifiedFileis older than the specifiedChronoLocalDateTimeat the system-default time zone.static booleanisFileOlder(java.io.File file, java.time.chrono.ChronoLocalDateTime<?> chronoLocalDateTime, java.time.ZoneId zoneId)Tests if the specifiedFileis older than the specifiedChronoLocalDateTimeat the specifiedZoneId.static booleanisFileOlder(java.io.File file, java.time.chrono.ChronoZonedDateTime<?> chronoZonedDateTime)Tests if the specifiedFileis older than the specifiedChronoZonedDateTime.static booleanisFileOlder(java.io.File file, java.time.Instant instant)Tests if the specifiedFileis older than the specifiedInstant.static booleanisFileOlder(java.io.File file, java.util.Date date)Tests if the specifiedFileis older than the specifiedDate.static booleanisRegularFile(java.io.File file, java.nio.file.LinkOption... options)Tests whether the specifiedFileis a regular file or not.static booleanisSymlink(java.io.File file)Tests whether the specified file is a symbolic link rather than an actual file.static java.util.Iterator<java.io.File>iterateFiles(java.io.File directory, java.lang.String[] extensions, boolean recursive)Iterates over the files in a given directory (and optionally its subdirectories) which match an array of extensions.static java.util.Iterator<java.io.File>iterateFiles(java.io.File directory, IOFileFilter fileFilter, IOFileFilter dirFilter)Iterates over the files in given directory (and optionally its subdirectories).static java.util.Iterator<java.io.File>iterateFilesAndDirs(java.io.File directory, IOFileFilter fileFilter, IOFileFilter dirFilter)Iterates over the files in given directory (and optionally its subdirectories).static longlastModified(java.io.File file)Returns the last modification time in milliseconds viaFiles.getLastModifiedTime(Path, LinkOption...).static longlastModifiedUnchecked(java.io.File file)Returns the last modification time in milliseconds viaFiles.getLastModifiedTime(Path, LinkOption...).static LineIteratorlineIterator(java.io.File file)Returns an Iterator for the lines in aFileusing the default encoding for the VM.static LineIteratorlineIterator(java.io.File file, java.lang.String charsetName)Returns an Iterator for the lines in aFile.static java.util.Collection<java.io.File>listFiles(java.io.File directory, java.lang.String[] extensions, boolean recursive)Finds files within a given directory (and optionally its subdirectories) which match an array of extensions.static java.util.Collection<java.io.File>listFiles(java.io.File directory, IOFileFilter fileFilter, IOFileFilter dirFilter)Finds files within a given directory (and optionally its subdirectories).static java.util.Collection<java.io.File>listFilesAndDirs(java.io.File directory, IOFileFilter fileFilter, IOFileFilter dirFilter)Finds files within a given directory (and optionally its subdirectories).static voidmoveDirectory(java.io.File srcDir, java.io.File destDir)Moves a directory.static voidmoveDirectoryToDirectory(java.io.File src, java.io.File destDir, boolean createDestDir)Moves a directory to another directory.static voidmoveFile(java.io.File srcFile, java.io.File destFile)Moves a file preserving attributes.static voidmoveFile(java.io.File srcFile, java.io.File destFile, java.nio.file.CopyOption... copyOptions)Moves a file.static voidmoveFileToDirectory(java.io.File srcFile, java.io.File destDir, boolean createDestDir)Moves a file to a directory.static voidmoveToDirectory(java.io.File src, java.io.File destDir, boolean createDestDir)Moves a file or directory to the destination directory.static java.io.FileInputStreamopenInputStream(java.io.File file)Opens aFileInputStreamfor the specified file, providing better error messages than simply callingnew FileInputStream(file).static java.io.FileOutputStreamopenOutputStream(java.io.File file)Opens aFileOutputStreamfor the specified file, checking and creating the parent directory if it does not exist.static java.io.FileOutputStreamopenOutputStream(java.io.File file, boolean append)Opens aFileOutputStreamfor the specified file, checking and creating the parent directory if it does not exist.static byte[]readFileToByteArray(java.io.File file)Reads the contents of a file into a byte array.static java.lang.StringreadFileToString(java.io.File file)Deprecated.2.5 usereadFileToString(File, Charset)instead (and specify the appropriate encoding)static java.lang.StringreadFileToString(java.io.File file, java.lang.String charsetName)Reads the contents of a file into a String.static java.lang.StringreadFileToString(java.io.File file, java.nio.charset.Charset charsetName)Reads the contents of a file into a String.static java.util.List<java.lang.String>readLines(java.io.File file)Deprecated.2.5 usereadLines(File, Charset)instead (and specify the appropriate encoding)static java.util.List<java.lang.String>readLines(java.io.File file, java.lang.String charsetName)Reads the contents of a file line by line to a List of Strings.static java.util.List<java.lang.String>readLines(java.io.File file, java.nio.charset.Charset charset)Reads the contents of a file line by line to a List of Strings.static longsizeOf(java.io.File file)Returns the size of the specified file or directory.static java.math.BigIntegersizeOfAsBigInteger(java.io.File file)Returns the size of the specified file or directory.static longsizeOfDirectory(java.io.File directory)Counts the size of a directory recursively (sum of the length of all files).static java.math.BigIntegersizeOfDirectoryAsBigInteger(java.io.File directory)Counts the size of a directory recursively (sum of the length of all files).static java.util.stream.Stream<java.io.File>streamFiles(java.io.File directory, boolean recursive, java.lang.String... extensions)Streams over the files in a given directory (and optionally its subdirectories) which match an array of extensions.static java.io.FiletoFile(java.net.URL url)Converts from aURLto aFile.static java.io.File[]toFiles(java.net.URL... urls)Converts each of an array ofURLto aFile.static voidtouch(java.io.File file)Implements the same behavior as the "touch" utility on Unix.static java.net.URL[]toURLs(java.io.File... files)Converts each of an array ofFileto aURL.static booleanwaitFor(java.io.File file, int seconds)Waits for NFS to propagate a file creation, imposing a timeout.static voidwrite(java.io.File file, java.lang.CharSequence data)Deprecated.2.5 usewrite(File, CharSequence, Charset)instead (and specify the appropriate encoding)static voidwrite(java.io.File file, java.lang.CharSequence data, boolean append)Deprecated.2.5 usewrite(File, CharSequence, Charset, boolean)instead (and specify the appropriate encoding)static voidwrite(java.io.File file, java.lang.CharSequence data, java.lang.String charsetName)Writes a CharSequence to a file creating the file if it does not exist.static voidwrite(java.io.File file, java.lang.CharSequence data, java.lang.String charsetName, boolean append)Writes a CharSequence to a file creating the file if it does not exist.static voidwrite(java.io.File file, java.lang.CharSequence data, java.nio.charset.Charset charset)Writes a CharSequence to a file creating the file if it does not exist.static voidwrite(java.io.File file, java.lang.CharSequence data, java.nio.charset.Charset charset, boolean append)Writes a CharSequence to a file creating the file if it does not exist.static voidwriteByteArrayToFile(java.io.File file, byte[] data)Writes a byte array to a file creating the file if it does not exist.static voidwriteByteArrayToFile(java.io.File file, byte[] data, boolean append)Writes a byte array to a file creating the file if it does not exist.static voidwriteByteArrayToFile(java.io.File file, byte[] data, int off, int len)Writeslenbytes from the specified byte array starting at offsetoffto a file, creating the file if it does not exist.static voidwriteByteArrayToFile(java.io.File file, byte[] data, int off, int len, boolean append)Writeslenbytes from the specified byte array starting at offsetoffto a file, creating the file if it does not exist.static voidwriteLines(java.io.File file, java.lang.String charsetName, java.util.Collection<?> lines)Writes thetoString()value of each item in a collection to the specifiedFileline by line.static voidwriteLines(java.io.File file, java.lang.String charsetName, java.util.Collection<?> lines, boolean append)Writes thetoString()value of each item in a collection to the specifiedFileline by line, optionally appending.static voidwriteLines(java.io.File file, java.lang.String charsetName, java.util.Collection<?> lines, java.lang.String lineEnding)Writes thetoString()value of each item in a collection to the specifiedFileline by line.static voidwriteLines(java.io.File file, java.lang.String charsetName, java.util.Collection<?> lines, java.lang.String lineEnding, boolean append)Writes thetoString()value of each item in a collection to the specifiedFileline by line.static voidwriteLines(java.io.File file, java.util.Collection<?> lines)Writes thetoString()value of each item in a collection to the specifiedFileline by line.static voidwriteLines(java.io.File file, java.util.Collection<?> lines, boolean append)Writes thetoString()value of each item in a collection to the specifiedFileline by line.static voidwriteLines(java.io.File file, java.util.Collection<?> lines, java.lang.String lineEnding)Writes thetoString()value of each item in a collection to the specifiedFileline by line.static voidwriteLines(java.io.File file, java.util.Collection<?> lines, java.lang.String lineEnding, boolean append)Writes thetoString()value of each item in a collection to the specifiedFileline by line.static voidwriteStringToFile(java.io.File file, java.lang.String data)Deprecated.2.5 usewriteStringToFile(File, String, Charset)instead (and specify the appropriate encoding)static voidwriteStringToFile(java.io.File file, java.lang.String data, boolean append)Deprecated.2.5 usewriteStringToFile(File, String, Charset, boolean)instead (and specify the appropriate encoding)static voidwriteStringToFile(java.io.File file, java.lang.String data, java.lang.String charsetName)Writes a String to a file creating the file if it does not exist.static voidwriteStringToFile(java.io.File file, java.lang.String data, java.lang.String charsetName, boolean append)Writes a String to a file creating the file if it does not exist.static voidwriteStringToFile(java.io.File file, java.lang.String data, java.nio.charset.Charset charset)Writes a String to a file creating the file if it does not exist.static voidwriteStringToFile(java.io.File file, java.lang.String data, java.nio.charset.Charset charset, boolean append)Writes a String to a file creating the file if it does not exist.
-
-
-
Field Detail
-
ONE_KB
public static final long ONE_KB
The number of bytes in a kilobyte.- See Also:
- Constant Field Values
-
ONE_KB_BI
public static final java.math.BigInteger ONE_KB_BI
The number of bytes in a kilobyte.- Since:
- 2.4
-
ONE_MB
public static final long ONE_MB
The number of bytes in a megabyte.- See Also:
- Constant Field Values
-
ONE_MB_BI
public static final java.math.BigInteger ONE_MB_BI
The number of bytes in a megabyte.- Since:
- 2.4
-
ONE_GB
public static final long ONE_GB
The number of bytes in a gigabyte.- See Also:
- Constant Field Values
-
ONE_GB_BI
public static final java.math.BigInteger ONE_GB_BI
The number of bytes in a gigabyte.- Since:
- 2.4
-
ONE_TB
public static final long ONE_TB
The number of bytes in a terabyte.- See Also:
- Constant Field Values
-
ONE_TB_BI
public static final java.math.BigInteger ONE_TB_BI
The number of bytes in a terabyte.- Since:
- 2.4
-
ONE_PB
public static final long ONE_PB
The number of bytes in a petabyte.- See Also:
- Constant Field Values
-
ONE_PB_BI
public static final java.math.BigInteger ONE_PB_BI
The number of bytes in a petabyte.- Since:
- 2.4
-
ONE_EB
public static final long ONE_EB
The number of bytes in an exabyte.- See Also:
- Constant Field Values
-
ONE_EB_BI
public static final java.math.BigInteger ONE_EB_BI
The number of bytes in an exabyte.- Since:
- 2.4
-
ONE_ZB
public static final java.math.BigInteger ONE_ZB
The number of bytes in a zettabyte.
-
ONE_YB
public static final java.math.BigInteger ONE_YB
The number of bytes in a yottabyte.
-
EMPTY_FILE_ARRAY
public static final java.io.File[] EMPTY_FILE_ARRAY
An empty array of typeFile.
-
-
Method Detail
-
byteCountToDisplaySize
public static java.lang.String byteCountToDisplaySize(java.math.BigInteger size)
Returns a human-readable version of the file size, where the input represents a specific number of bytes.If the size is over 1GB, the size is returned as the number of whole GB, i.e. the size is rounded down to the nearest GB boundary.
Similarly for the 1MB and 1KB boundaries.
- Parameters:
size- the number of bytes- Returns:
- a human-readable display value (includes units - EB, PB, TB, GB, MB, KB or bytes)
- Throws:
java.lang.NullPointerException- if the givenBigIntegerisnull.- Since:
- 2.4
- See Also:
- IO-226 - should the rounding be changed?
-
byteCountToDisplaySize
public static java.lang.String byteCountToDisplaySize(long size)
Returns a human-readable version of the file size, where the input represents a specific number of bytes.If the size is over 1GB, the size is returned as the number of whole GB, i.e. the size is rounded down to the nearest GB boundary.
Similarly for the 1MB and 1KB boundaries.
- Parameters:
size- the number of bytes- Returns:
- a human-readable display value (includes units - EB, PB, TB, GB, MB, KB or bytes)
- See Also:
- IO-226 - should the rounding be changed?
-
checksum
public static java.util.zip.Checksum checksum(java.io.File file, java.util.zip.Checksum checksum) throws java.io.IOExceptionComputes the checksum of a file using the specified checksum object. Multiple files may be checked using oneChecksuminstance if desired simply by reusing the same checksum object. For example:long checksum = FileUtils.checksum(file, new CRC32()).getValue();
- Parameters:
file- the file to checksum, must not benullchecksum- the checksum object to be used, must not benull- Returns:
- the checksum specified, updated with the content of the file
- Throws:
java.lang.NullPointerException- if the givenFileisnull.java.lang.NullPointerException- if the givenChecksumisnull.java.lang.IllegalArgumentException- if the givenFiledoes not exist or is not a file.java.io.IOException- if an IO error occurs reading the file.- Since:
- 1.3
-
checksumCRC32
public static long checksumCRC32(java.io.File file) throws java.io.IOExceptionComputes 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:
java.lang.NullPointerException- if the givenFileisnull.java.lang.IllegalArgumentException- if the givenFiledoes not exist or is not a file.java.io.IOException- if an IO error occurs reading the file.- Since:
- 1.3
-
cleanDirectory
public static void cleanDirectory(java.io.File directory) throws java.io.IOExceptionCleans a directory without deleting it.- Parameters:
directory- directory to clean- Throws:
java.lang.NullPointerException- if the givenFileisnull.java.lang.IllegalArgumentException- if directory does not exist or is not a directory.java.io.IOException- if an I/O error occurs.- See Also:
forceDelete(File)
-
contentEquals
public static boolean contentEquals(java.io.File file1, java.io.File file2) throws java.io.IOExceptionTests 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:
java.lang.IllegalArgumentException- when an input is not a file.java.io.IOException- If an I/O error occurs.- See Also:
PathUtils.fileContentEquals(Path,Path,java.nio.file.LinkOption[],java.nio.file.OpenOption...)
-
contentEqualsIgnoreEOL
public static boolean contentEqualsIgnoreEOL(java.io.File file1, java.io.File file2, java.lang.String charsetName) throws java.io.IOExceptionCompares 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:
java.lang.IllegalArgumentException- when an input is not a file.java.io.IOException- in case of an I/O error.java.nio.charset.UnsupportedCharsetException- If the named charset is unavailable (unchecked exception).- Since:
- 2.2
- See Also:
IOUtils.contentEqualsIgnoreEOL(Reader, Reader)
-
convertFileCollectionToFileArray
public static java.io.File[] convertFileCollectionToFileArray(java.util.Collection<java.io.File> files)
Converts a Collection containing java.io.File instanced into array representation. This is to account for the difference between File.listFiles() and FileUtils.listFiles().- Parameters:
files- a Collection containing java.io.File instances- Returns:
- an array of java.io.File
-
copyDirectory
public static void copyDirectory(java.io.File srcDir, java.io.File destDir) throws java.io.IOExceptionCopies 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:
java.lang.NullPointerException- if any of the givenFiles arenull.java.lang.IllegalArgumentException- if the source or destination is invalid.java.io.FileNotFoundException- if the source does not exist.java.io.IOException- if an error occurs or setting the last-modified time didn't succeeded.- Since:
- 1.1
-
copyDirectory
public static void copyDirectory(java.io.File srcDir, java.io.File destDir, boolean preserveFileDate) throws java.io.IOExceptionCopies a whole directory to a new location.This method copies the contents of the specified source directory to within the specified destination directory.
The destination directory is created if it does not exist. If the destination directory did exist, then this method merges the source with the destination, with the source taking precedence.
Note: Setting
preserveFileDatetotruetries to preserve the files' last modified date/times usingFile.setLastModified(long), however it is not guaranteed that those operations will succeed. If the modification operation fails, 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:
java.lang.NullPointerException- if any of the givenFiles arenull.java.lang.IllegalArgumentException- if the source or destination is invalid.java.io.FileNotFoundException- if the source does not exist.java.io.IOException- if an error occurs or setting the last-modified time didn't succeeded.- Since:
- 1.1
-
copyDirectory
public static void copyDirectory(java.io.File srcDir, java.io.File destDir, java.io.FileFilter filter) throws java.io.IOExceptionCopies 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:
java.lang.NullPointerException- if any of the givenFiles arenull.java.lang.IllegalArgumentException- if the source or destination is invalid.java.io.FileNotFoundException- if the source does not exist.java.io.IOException- if an error occurs or setting the last-modified time didn't succeeded.- Since:
- 1.4
-
copyDirectory
public static void copyDirectory(java.io.File srcDir, java.io.File destDir, java.io.FileFilter filter, boolean preserveFileDate) throws java.io.IOExceptionCopies 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 onlypreserveFileDatetotruetries 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:
java.lang.NullPointerException- if any of the givenFiles arenull.java.lang.IllegalArgumentException- if the source or destination is invalid.java.io.FileNotFoundException- if the source does not exist.java.io.IOException- if an error occurs or setting the last-modified time didn't succeeded.- Since:
- 1.4
-
copyDirectory
public static void copyDirectory(java.io.File srcDir, java.io.File destDir, java.io.FileFilter fileFilter, boolean preserveFileDate, java.nio.file.CopyOption... copyOptions) throws java.io.IOExceptionCopies 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 onlypreserveFileDatetotruetries 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 benulldestDir- the new directory, must not benullfileFilter- 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:
java.lang.NullPointerException- if any of the givenFiles arenull.java.lang.IllegalArgumentException- if the source or destination is invalid.java.io.FileNotFoundException- if the source does not exist.java.io.IOException- if an error occurs or setting the last-modified time didn't succeeded.- Since:
- 2.8.0
-
copyDirectoryToDirectory
public static void copyDirectoryToDirectory(java.io.File sourceDir, java.io.File destinationDir) throws java.io.IOExceptionCopies 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:
java.lang.NullPointerException- if any of the givenFiles arenull.java.lang.IllegalArgumentException- if the source or destination is invalid.java.io.FileNotFoundException- if the source does not exist.java.io.IOException- if an error occurs or setting the last-modified time didn't succeeded.- Since:
- 1.2
-
copyFile
public static void copyFile(java.io.File srcFile, java.io.File destFile) throws java.io.IOExceptionCopies 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:
java.lang.NullPointerException- if any of the givenFiles arenull.java.io.IOException- if source or destination is invalid.java.io.IOException- if an error occurs or setting the last-modified time didn't succeeded.java.io.IOException- if the output file length is not the same as the input file length after the copy completes.- See Also:
copyFileToDirectory(File, File),copyFile(File, File, boolean)
-
copyFile
public static void copyFile(java.io.File srcFile, java.io.File destFile, boolean preserveFileDate) throws java.io.IOExceptionCopies 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
preserveFileDatetotruetries to preserve the file's last modified date/times usingFile.setLastModified(long), however it is not guaranteed that the operation will succeed. If the modification operation fails, 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:
java.lang.NullPointerException- if any of the givenFiles arenull.java.io.IOException- if source or destination is invalid.java.io.IOException- if an error occurs or setting the last-modified time didn't succeeded.java.io.IOException- if the output file length is not the same as the input file length after the copy completes- See Also:
copyFile(File, File, boolean, CopyOption...)
-
copyFile
public static void copyFile(java.io.File srcFile, java.io.File destFile, boolean preserveFileDate, java.nio.file.CopyOption... copyOptions) throws java.io.IOExceptionCopies 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
preserveFileDatetotruetries to preserve the file's last modified date/times usingFile.setLastModified(long), however it is not guaranteed that the operation will succeed. If the modification operation fails, 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:
java.lang.NullPointerException- if any of the givenFiles arenull.java.io.FileNotFoundException- if the source does not exist.java.lang.IllegalArgumentException- if source is not a file.java.io.IOException- if the output file length is not the same as the input file length after the copy completes.java.io.IOException- if an I/O error occurs, or setting the last-modified time didn't succeeded.- Since:
- 2.8.0
- See Also:
copyFileToDirectory(File, File, boolean)
-
copyFile
public static void copyFile(java.io.File srcFile, java.io.File destFile, java.nio.file.CopyOption... copyOptions) throws java.io.IOExceptionCopies 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:
java.lang.NullPointerException- if any of the givenFiles arenull.java.io.FileNotFoundException- if the source does not exist.java.lang.IllegalArgumentException- if source is not a file.java.io.IOException- if the output file length is not the same as the input file length after the copy completes.java.io.IOException- if an I/O error occurs.- Since:
- 2.9.0
- See Also:
StandardCopyOption
-
copyFile
public static long copyFile(java.io.File input, java.io.OutputStream output) throws java.io.IOExceptionCopies bytes from aFileto anOutputStream.This method buffers the input internally, so there is no need to use a
BufferedInputStream.- Parameters:
input- theFileto read.output- theOutputStreamto write.- Returns:
- the number of bytes copied
- Throws:
java.lang.NullPointerException- if the File isnull.java.lang.NullPointerException- if the OutputStream isnull.java.io.IOException- if an I/O error occurs.- Since:
- 2.1
-
copyFileToDirectory
public static void copyFileToDirectory(java.io.File srcFile, java.io.File destDir) throws java.io.IOExceptionCopies 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:
java.lang.NullPointerException- if any of the givenFiles arenull.java.lang.IllegalArgumentException- if source or destination is invalid.java.io.IOException- if an error occurs or setting the last-modified time didn't succeeded.- See Also:
copyFile(File, File, boolean)
-
copyFileToDirectory
public static void copyFileToDirectory(java.io.File sourceFile, java.io.File destinationDir, boolean preserveFileDate) throws java.io.IOExceptionCopies a file to a directory optionally preserving the file date.This method copies the contents of the specified source file to a file of the same name in the specified destination directory. The destination directory is created if it does not exist. If the destination file exists, then this method will overwrite it.
Note: Setting
preserveFileDatetotruetries to preserve the file's last modified date/times usingFile.setLastModified(long), however it is not guaranteed that the operation will succeed. If the modification operation fails, 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:
java.lang.NullPointerException- if any of the givenFiles arenull.java.io.IOException- if an error occurs or setting the last-modified time didn't succeeded.java.io.IOException- if the output file length is not the same as the input file length after the copy completes.- Since:
- 1.3
- See Also:
copyFile(File, File, CopyOption...)
-
copyInputStreamToFile
public static void copyInputStreamToFile(java.io.InputStream source, java.io.File destination) throws java.io.IOExceptionCopies bytes from anInputStreamsourceto a filedestination. The directories up todestinationwill be created if they don't already exist.destinationwill be overwritten if it already exists.The
sourcestream is closed.See
copyToFile(InputStream, File)for a method that does not close the input stream.- Parameters:
source- theInputStreamto copy bytes from, must not benull, will be closeddestination- the non-directoryFileto write bytes to (possibly overwriting), must not benull- Throws:
java.io.IOException- ifdestinationis a directoryjava.io.IOException- ifdestinationcannot be writtenjava.io.IOException- ifdestinationneeds creating but can't bejava.io.IOException- if an IO error occurs during copying- Since:
- 2.0
-
copyToDirectory
public static void copyToDirectory(java.io.File sourceFile, java.io.File destinationDir) throws java.io.IOExceptionCopies 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:
java.lang.NullPointerException- if any of the givenFiles arenull.java.lang.IllegalArgumentException- if the source or destination is invalid.java.io.FileNotFoundException- if the source does not exist.java.io.IOException- if an error occurs or setting the last-modified time didn't succeeded.- Since:
- 2.6
- See Also:
copyDirectoryToDirectory(File, File),copyFileToDirectory(File, File)
-
copyToDirectory
public static void copyToDirectory(java.lang.Iterable<java.io.File> sourceIterable, java.io.File destinationDir) throws java.io.IOExceptionCopies 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:
java.lang.NullPointerException- if any of the givenFiles arenull.java.io.IOException- if source or destination is invalid.java.io.IOException- if an error occurs or setting the last-modified time didn't succeeded.- Since:
- 2.6
- See Also:
copyFileToDirectory(File, File)
-
copyToFile
public static void copyToFile(java.io.InputStream inputStream, java.io.File file) throws java.io.IOExceptionCopies bytes from anInputStreamsource to aFiledestination. The directories up todestinationwill be created if they don't already exist.destinationwill be overwritten if it already exists. Thesourcestream is left open, e.g. for use withZipInputStream. SeecopyInputStreamToFile(InputStream, File)for a method that closes the input stream.- Parameters:
inputStream- theInputStreamto copy bytes from, must not benullfile- the non-directoryFileto write bytes to (possibly overwriting), must not benull- Throws:
java.lang.NullPointerException- if the InputStream isnull.java.lang.NullPointerException- if the File isnull.java.lang.IllegalArgumentException- if the file object is a directory.java.lang.IllegalArgumentException- if the file is not writable.java.io.IOException- if the directories could not be created.java.io.IOException- if an IO error occurs during copying.- Since:
- 2.5
-
copyURLToFile
public static void copyURLToFile(java.net.URL source, java.io.File destination) throws java.io.IOExceptionCopies bytes from the URLsourceto a filedestination. The directories up todestinationwill be created if they don't already exist.destinationwill be overwritten if it already exists.Warning: this method does not set a connection or read timeout and thus might block forever. Use
copyURLToFile(URL, File, int, int)with reasonable timeouts to prevent this.- Parameters:
source- theURLto copy bytes from, must not benulldestination- the non-directoryFileto write bytes to (possibly overwriting), must not benull- Throws:
java.io.IOException- ifsourceURL cannot be openedjava.io.IOException- ifdestinationis a directoryjava.io.IOException- ifdestinationcannot be writtenjava.io.IOException- ifdestinationneeds creating but can't bejava.io.IOException- if an IO error occurs during copying
-
copyURLToFile
public static void copyURLToFile(java.net.URL source, java.io.File destination, int connectionTimeoutMillis, int readTimeoutMillis) throws java.io.IOExceptionCopies bytes from the URLsourceto a filedestination. The directories up todestinationwill be created if they don't already exist.destinationwill be overwritten if it already exists.- Parameters:
source- theURLto copy bytes from, must not benulldestination- the non-directoryFileto write bytes to (possibly overwriting), must not benullconnectionTimeoutMillis- the number of milliseconds until this method will timeout if no connection could be established to thesourcereadTimeoutMillis- the number of milliseconds until this method will timeout if no data could be read from thesource- Throws:
java.io.IOException- ifsourceURL cannot be openedjava.io.IOException- ifdestinationis a directoryjava.io.IOException- ifdestinationcannot be writtenjava.io.IOException- ifdestinationneeds creating but can't bejava.io.IOException- if an IO error occurs during copying- Since:
- 2.0
-
createParentDirectories
public static java.io.File createParentDirectories(java.io.File file) throws java.io.IOExceptionCreates all parent directories for a File object.- Parameters:
file- the File that may need parents, may be null.- Returns:
- The parent directory, or
nullif the given file does not name a parent - Throws:
java.io.IOException- if the directory was not created along with all its parent directories.java.io.IOException- if the given file object is not null and not a directory.- Since:
- 2.9.0
-
delete
public static java.io.File delete(java.io.File file) throws java.io.IOExceptionDeletes 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:
java.io.IOException- if the file cannot be deleted.- Since:
- 2.9.0
- See Also:
File.delete()
-
deleteDirectory
public static void deleteDirectory(java.io.File directory) throws java.io.IOExceptionDeletes a directory recursively.- Parameters:
directory- directory to delete- Throws:
java.io.IOException- in case deletion is unsuccessfuljava.lang.IllegalArgumentException- ifdirectoryis not a directory
-
deleteQuietly
public static boolean deleteQuietly(java.io.File file)
Deletes a file, never throwing an exception. If file is a directory, delete it and all sub-directories.The difference between File.delete() and this method are:
- A directory to be deleted does not have to be empty.
- No exceptions are thrown when a file or directory cannot be deleted.
- Parameters:
file- file or directory to delete, can benull- Returns:
trueif the file or directory was deleted, otherwisefalse- Since:
- 1.4
-
directoryContains
public static boolean directoryContains(java.io.File directory, java.io.File child) throws java.io.IOExceptionDetermines whether theparentdirectory contains thechildelement (a file or directory).Files are normalized before comparison.
Edge cases:- A
directorymust not be null: if null, throw IllegalArgumentException - A
directorymust be a directory: if not a directory, throw IllegalArgumentException - A directory does not contain itself: return false
- A null child file is not contained in any parent: return false
- Parameters:
directory- the file to consider as the parent.child- the file to consider as the child.- Returns:
- true is the candidate leaf is under by the specified composite. False otherwise.
- Throws:
java.io.IOException- if an IO error occurs while checking the files.java.lang.NullPointerException- if the givenFileisnull.java.lang.IllegalArgumentException- if the givenFiledoes not exist or is not a directory.- Since:
- 2.2
- See Also:
FilenameUtils.directoryContains(String, String)
- A
-
forceDelete
public static void forceDelete(java.io.File file) throws java.io.IOExceptionDeletes 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:
java.lang.NullPointerException- if the file isnull.java.io.FileNotFoundException- if the file was not found.java.io.IOException- in case deletion is unsuccessful.
-
forceDeleteOnExit
public static void forceDeleteOnExit(java.io.File file) throws java.io.IOExceptionSchedules 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:
java.lang.NullPointerException- if the file isnull.java.io.IOException- in case deletion is unsuccessful.
-
forceMkdir
public static void forceMkdir(java.io.File directory) throws java.io.IOExceptionMakes 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:
java.io.IOException- if the directory was not created along with all its parent directories.java.io.IOException- if the given file object is not a directory.java.lang.SecurityException- SeeFile.mkdirs().
-
forceMkdirParent
public static void forceMkdirParent(java.io.File file) throws java.io.IOExceptionMakes 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:
java.lang.NullPointerException- if the file isnull.java.io.IOException- if the parent directory cannot be created.- Since:
- 2.5
-
getFile
public static java.io.File getFile(java.io.File directory, java.lang.String... names)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
public static java.io.File getFile(java.lang.String... names)
Construct a file from the set of name elements.- Parameters:
names- the name elements.- Returns:
- the file.
- Since:
- 2.1
-
getTempDirectory
public static java.io.File getTempDirectory()
Returns aFilerepresenting the system temporary directory.- Returns:
- the system temporary directory.
- Since:
- 2.0
-
getTempDirectoryPath
public static java.lang.String getTempDirectoryPath()
Returns the path to the system temporary directory.- Returns:
- the path to the system temporary directory.
- Since:
- 2.0
-
getUserDirectory
public static java.io.File getUserDirectory()
Returns aFilerepresenting the user's home directory.- Returns:
- the user's home directory.
- Since:
- 2.0
-
getUserDirectoryPath
public static java.lang.String getUserDirectoryPath()
Returns the path to the user's home directory.- Returns:
- the path to the user's home directory.
- Since:
- 2.0
-
isDirectory
public static boolean isDirectory(java.io.File file, java.nio.file.LinkOption... options)Tests whether the specifiedFileis 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:
trueif the file is a directory;falseif 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:
java.lang.SecurityException- In the case of the default provider, and a security manager is installed, thecheckReadmethod is invoked to check read access to the directory.- Since:
- 2.9.0
-
isEmptyDirectory
public static boolean isEmptyDirectory(java.io.File directory) throws java.io.IOExceptionTests whether the directory is empty.- Parameters:
directory- the directory to query.- Returns:
- whether the directory is empty.
- Throws:
java.io.IOException- if an I/O error occurs.java.nio.file.NotDirectoryException- if the file could not otherwise be opened because it is not a directory (optional specific exception).- Since:
- 2.9.0
-
isFileNewer
public static boolean isFileNewer(java.io.File file, java.time.chrono.ChronoLocalDate chronoLocalDate)Tests if the specifiedFileis newer than the specifiedChronoLocalDateat 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)wherezoneIdis a validZoneId.- Parameters:
file- theFileof which the modification date must be compared.chronoLocalDate- the date reference.- Returns:
- true if the
Fileexists and has been modified after the givenChronoLocalDateat the current time. - Throws:
java.lang.NullPointerException- if the file or local date isnull.- Since:
- 2.8.0
-
isFileNewer
public static boolean isFileNewer(java.io.File file, java.time.chrono.ChronoLocalDate chronoLocalDate, java.time.LocalTime localTime)Tests if the specifiedFileis newer than the specifiedChronoLocalDateat 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)wherezoneIdis a validZoneId.- Parameters:
file- theFileof which the modification date must be compared.chronoLocalDate- the date reference.localTime- the time reference.- Returns:
- true if the
Fileexists and has been modified after the givenChronoLocalDateat the given time. - Throws:
java.lang.NullPointerException- if the file, local date or zone ID isnull.- Since:
- 2.8.0
-
isFileNewer
public static boolean isFileNewer(java.io.File file, java.time.chrono.ChronoLocalDateTime<?> chronoLocalDateTime)Tests if the specifiedFileis newer than the specifiedChronoLocalDateTimeat 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)wherezoneIdis a validZoneId.- Parameters:
file- theFileof which the modification date must be compared.chronoLocalDateTime- the date reference.- Returns:
- true if the
Fileexists and has been modified after the givenChronoLocalDateTimeat the system-default time zone. - Throws:
java.lang.NullPointerException- if the file or local date time isnull.- Since:
- 2.8.0
-
isFileNewer
public static boolean isFileNewer(java.io.File file, java.time.chrono.ChronoLocalDateTime<?> chronoLocalDateTime, java.time.ZoneId zoneId)Tests if the specifiedFileis newer than the specifiedChronoLocalDateTimeat the specifiedZoneId.- Parameters:
file- theFileof which the modification date must be compared.chronoLocalDateTime- the date reference.zoneId- the time zone.- Returns:
- true if the
Fileexists and has been modified after the givenChronoLocalDateTimeat the givenZoneId. - Throws:
java.lang.NullPointerException- if the file, local date time or zone ID isnull.- Since:
- 2.8.0
-
isFileNewer
public static boolean isFileNewer(java.io.File file, java.time.chrono.ChronoZonedDateTime<?> chronoZonedDateTime)Tests if the specifiedFileis newer than the specifiedChronoZonedDateTime.- Parameters:
file- theFileof which the modification date must be compared.chronoZonedDateTime- the date reference.- Returns:
- true if the
Fileexists and has been modified after the givenChronoZonedDateTime. - Throws:
java.lang.NullPointerException- if the file or zoned date time isnull.- Since:
- 2.8.0
-
isFileNewer
public static boolean isFileNewer(java.io.File file, java.util.Date date)Tests if the specifiedFileis newer than the specifiedDate.- Parameters:
file- theFileof which the modification date must be compared.date- the date reference.- Returns:
- true if the
Fileexists and has been modified after the givenDate. - Throws:
java.lang.NullPointerException- if the file or date isnull.
-
isFileNewer
public static boolean isFileNewer(java.io.File file, java.io.File reference)Tests if the specifiedFileis newer than the referenceFile.- Parameters:
file- theFileof which the modification date must be compared.reference- theFileof which the modification date is used.- Returns:
- true if the
Fileexists and has been modified more recently than the referenceFile. - Throws:
java.lang.NullPointerException- if the file or reference file isnull.java.lang.IllegalArgumentException- if the reference file doesn't exist.
-
isFileNewer
public static boolean isFileNewer(java.io.File file, java.time.Instant instant)Tests if the specifiedFileis newer than the specifiedInstant.- Parameters:
file- theFileof which the modification date must be compared.instant- the date reference.- Returns:
- true if the
Fileexists and has been modified after the givenInstant. - Throws:
java.lang.NullPointerException- if the file or instant isnull.- Since:
- 2.8.0
-
isFileNewer
public static boolean isFileNewer(java.io.File file, long timeMillis)Tests if the specifiedFileis newer than the specified time reference.- Parameters:
file- theFileof 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
Fileexists and has been modified after the given time reference. - Throws:
java.lang.NullPointerException- if the file isnull.
-
isFileOlder
public static boolean isFileOlder(java.io.File file, java.time.chrono.ChronoLocalDate chronoLocalDate)Tests if the specifiedFileis older than the specifiedChronoLocalDateat 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)wherezoneIdis a validZoneId.- Parameters:
file- theFileof which the modification date must be compared.chronoLocalDate- the date reference.- Returns:
- true if the
Fileexists and has been modified before the givenChronoLocalDateat the current time. - Throws:
java.lang.NullPointerException- if the file or local date isnull.- Since:
- 2.8.0
- See Also:
ZoneId.systemDefault(),LocalTime.now()
-
isFileOlder
public static boolean isFileOlder(java.io.File file, java.time.chrono.ChronoLocalDate chronoLocalDate, java.time.LocalTime localTime)Tests if the specifiedFileis older than the specifiedChronoLocalDateat 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)wherezoneIdis a validZoneId.- Parameters:
file- theFileof which the modification date must be compared.chronoLocalDate- the date reference.localTime- the time reference.- Returns:
- true if the
Fileexists and has been modified before the givenChronoLocalDateat the specified time. - Throws:
java.lang.NullPointerException- if the file, local date or local time isnull.- Since:
- 2.8.0
- See Also:
ZoneId.systemDefault()
-
isFileOlder
public static boolean isFileOlder(java.io.File file, java.time.chrono.ChronoLocalDateTime<?> chronoLocalDateTime)Tests if the specifiedFileis older than the specifiedChronoLocalDateTimeat 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)wherezoneIdis a validZoneId.- Parameters:
file- theFileof which the modification date must be compared.chronoLocalDateTime- the date reference.- Returns:
- true if the
Fileexists and has been modified before the givenChronoLocalDateTimeat the system-default time zone. - Throws:
java.lang.NullPointerException- if the file or local date time isnull.- Since:
- 2.8.0
- See Also:
ZoneId.systemDefault()
-
isFileOlder
public static boolean isFileOlder(java.io.File file, java.time.chrono.ChronoLocalDateTime<?> chronoLocalDateTime, java.time.ZoneId zoneId)Tests if the specifiedFileis older than the specifiedChronoLocalDateTimeat the specifiedZoneId.- Parameters:
file- theFileof which the modification date must be compared.chronoLocalDateTime- the date reference.zoneId- the time zone.- Returns:
- true if the
Fileexists and has been modified before the givenChronoLocalDateTimeat the givenZoneId. - Throws:
java.lang.NullPointerException- if the file, local date time or zone ID isnull.- Since:
- 2.8.0
-
isFileOlder
public static boolean isFileOlder(java.io.File file, java.time.chrono.ChronoZonedDateTime<?> chronoZonedDateTime)Tests if the specifiedFileis older than the specifiedChronoZonedDateTime.- Parameters:
file- theFileof which the modification date must be compared.chronoZonedDateTime- the date reference.- Returns:
- true if the
Fileexists and has been modified before the givenChronoZonedDateTime. - Throws:
java.lang.NullPointerException- if the file or zoned date time isnull.- Since:
- 2.8.0
-
isFileOlder
public static boolean isFileOlder(java.io.File file, java.util.Date date)Tests if the specifiedFileis older than the specifiedDate.- Parameters:
file- theFileof which the modification date must be compared.date- the date reference.- Returns:
- true if the
Fileexists and has been modified before the givenDate. - Throws:
java.lang.NullPointerException- if the file or date isnull.
-
isFileOlder
public static boolean isFileOlder(java.io.File file, java.io.File reference)Tests if the specifiedFileis older than the referenceFile.- Parameters:
file- theFileof which the modification date must be compared.reference- theFileof which the modification date is used.- Returns:
- true if the
Fileexists and has been modified before the referenceFile. - Throws:
java.lang.NullPointerException- if the file or reference file isnull.java.lang.IllegalArgumentException- if the reference file doesn't exist.
-
isFileOlder
public static boolean isFileOlder(java.io.File file, java.time.Instant instant)Tests if the specifiedFileis older than the specifiedInstant.- Parameters:
file- theFileof which the modification date must be compared.instant- the date reference.- Returns:
- true if the
Fileexists and has been modified before the givenInstant. - Throws:
java.lang.NullPointerException- if the file or instant isnull.- Since:
- 2.8.0
-
isFileOlder
public static boolean isFileOlder(java.io.File file, long timeMillis)Tests if the specifiedFileis older than the specified time reference.- Parameters:
file- theFileof 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
Fileexists and has been modified before the given time reference. - Throws:
java.lang.NullPointerException- if the file isnull.
-
isRegularFile
public static boolean isRegularFile(java.io.File file, java.nio.file.LinkOption... options)Tests whether the specifiedFileis 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:
trueif the file is a regular file;falseif 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:
java.lang.SecurityException- In the case of the default provider, and a security manager is installed, thecheckReadmethod is invoked to check read access to the directory.- Since:
- 2.9.0
-
isSymlink
public static boolean isSymlink(java.io.File file)
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:
Files.isSymbolicLink(Path)
-
iterateFiles
public static java.util.Iterator<java.io.File> iterateFiles(java.io.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:
FileFilterUtils,NameFileFilter
-
iterateFiles
public static java.util.Iterator<java.io.File> iterateFiles(java.io.File directory, java.lang.String[] extensions, boolean recursive)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 java.util.Iterator<java.io.File> iterateFilesAndDirs(java.io.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:
FileFilterUtils,NameFileFilter
-
lastModified
public static long lastModified(java.io.File file) throws java.io.IOExceptionReturns 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:
java.io.IOException- if an I/O error occurs.- Since:
- 2.9.0
-
lastModifiedUnchecked
public static long lastModifiedUnchecked(java.io.File file)
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:
java.io.UncheckedIOException- if an I/O error occurs.- Since:
- 2.9.0
-
lineIterator
public static LineIterator lineIterator(java.io.File file) throws java.io.IOException
Returns an Iterator for the lines in aFileusing the default encoding for the VM.- Parameters:
file- the file to open for input, must not benull- Returns:
- an Iterator of the lines in the file, never
null - Throws:
java.lang.NullPointerException- if file isnull.java.io.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.java.io.IOException- if an I/O error occurs.- Since:
- 1.3
- See Also:
lineIterator(File, String)
-
lineIterator
public static LineIterator lineIterator(java.io.File file, java.lang.String charsetName) throws java.io.IOException
Returns an Iterator for the lines in aFile.This method opens an
InputStreamfor the file. When you have finished with the iterator you should close the stream to free internal resources. This can be done by calling theLineIterator.close()orLineIterator.closeQuietly(LineIterator)method.The recommended usage pattern is:
LineIterator it = FileUtils.lineIterator(file, "UTF-8"); try { while (it.hasNext()) { String line = it.nextLine(); /// do something with line } } finally { LineIterator.closeQuietly(iterator); }If an exception occurs during the creation of the iterator, the underlying stream is closed.
- Parameters:
file- the file to open for input, must not benullcharsetName- the name of the requested charset,nullmeans platform default- Returns:
- an Iterator of the lines in the file, never
null - Throws:
java.lang.NullPointerException- if file isnull.java.io.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.java.io.IOException- if an I/O error occurs.- Since:
- 1.2
-
listFiles
public static java.util.Collection<java.io.File> listFiles(java.io.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.INSTANCEto 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.INSTANCEto match all directories.- Returns:
- a collection of java.io.File with the matching files
- See Also:
FileFilterUtils,NameFileFilter
-
listFiles
public static java.util.Collection<java.io.File> listFiles(java.io.File directory, java.lang.String[] extensions, boolean recursive)Finds files within a given directory (and optionally its subdirectories) which match an array of extensions.- Parameters:
directory- the directory to search inextensions- an array of extensions, ex. {"java","xml"}. If this parameter isnull, all files are returned.recursive- if true all subdirectories are searched as well- Returns:
- a collection of java.io.File with the matching files
-
listFilesAndDirs
public static java.util.Collection<java.io.File> listFilesAndDirs(java.io.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:
listFiles(java.io.File, java.io.FileFilter),FileFilterUtils,NameFileFilter
-
moveDirectory
public static void moveDirectory(java.io.File srcDir, java.io.File destDir) throws java.io.IOExceptionMoves 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:
java.lang.NullPointerException- if any of the givenFiles arenull.java.lang.IllegalArgumentException- if the source or destination is invalid.java.io.FileNotFoundException- if the source does not exist.java.io.IOException- if an error occurs or setting the last-modified time didn't succeeded.- Since:
- 1.4
-
moveDirectoryToDirectory
public static void moveDirectoryToDirectory(java.io.File src, java.io.File destDir, boolean createDestDir) throws java.io.IOExceptionMoves a directory to another directory.- Parameters:
src- the file to be moved.destDir- the destination file.createDestDir- Iftruecreate the destination directory, otherwise iffalsethrow an IOException.- Throws:
java.lang.NullPointerException- if any of the givenFiles arenull.java.lang.IllegalArgumentException- if the source or destination is invalid.java.io.FileNotFoundException- if the source does not exist.java.io.IOException- if an error occurs or setting the last-modified time didn't succeeded.- Since:
- 1.4
-
moveFile
public static void moveFile(java.io.File srcFile, java.io.File destFile) throws java.io.IOExceptionMoves 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:
java.lang.NullPointerException- if any of the givenFiles arenull.FileExistsException- if the destination file exists.java.io.IOException- if source or destination is invalid.java.io.IOException- if an error occurs.- Since:
- 1.4
-
moveFile
public static void moveFile(java.io.File srcFile, java.io.File destFile, java.nio.file.CopyOption... copyOptions) throws java.io.IOExceptionMoves 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:
java.lang.NullPointerException- if any of the givenFiles arenull.FileExistsException- if the destination file exists.java.io.IOException- if source or destination is invalid.java.io.IOException- if an error occurs or setting the last-modified time didn't succeeded.- Since:
- 2.9.0
-
moveFileToDirectory
public static void moveFileToDirectory(java.io.File srcFile, java.io.File destDir, boolean createDestDir) throws java.io.IOExceptionMoves a file to a directory.- Parameters:
srcFile- the file to be moved.destDir- the destination file.createDestDir- Iftruecreate the destination directory, otherwise iffalsethrow an IOException.- Throws:
java.lang.NullPointerException- if any of the givenFiles arenull.FileExistsException- if the destination file exists.java.io.IOException- if source or destination is invalid.java.io.IOException- if an error occurs or setting the last-modified time didn't succeeded.- Since:
- 1.4
-
moveToDirectory
public static void moveToDirectory(java.io.File src, java.io.File destDir, boolean createDestDir) throws java.io.IOExceptionMoves 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- Iftruecreate the destination directory, otherwise iffalsethrow an IOException.- Throws:
java.lang.NullPointerException- if any of the givenFiles arenull.FileExistsException- if the directory or file exists in the destination directory.java.io.IOException- if source or destination is invalid.java.io.IOException- if an error occurs or setting the last-modified time didn't succeeded.- Since:
- 1.4
-
openInputStream
public static java.io.FileInputStream openInputStream(java.io.File file) throws java.io.IOExceptionOpens aFileInputStreamfor the specified file, providing better error messages than simply callingnew FileInputStream(file).At the end of the method either the stream will be successfully opened, or an exception will have been thrown.
An exception is thrown if the file does not exist. An exception is thrown if the file object exists but is a directory. An exception is thrown if the file exists but cannot be read.
- Parameters:
file- the file to open for input, must not benull- Returns:
- a new
FileInputStreamfor the specified file - Throws:
java.lang.NullPointerException- if file isnull.java.io.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.java.io.IOException- See FileNotFoundException above, FileNotFoundException is a subclass of IOException.- Since:
- 1.3
-
openOutputStream
public static java.io.FileOutputStream openOutputStream(java.io.File file) throws java.io.IOExceptionOpens aFileOutputStreamfor the specified file, checking and creating the parent directory if it does not exist.At the end of the method either the stream will be successfully opened, or an exception will have been thrown.
The parent directory will be created if it does not exist. The file will be created if it does not exist. An exception is thrown if the file object exists but is a directory. An exception is thrown if the file exists but cannot be written to. An exception is thrown if the parent directory cannot be created.
- Parameters:
file- the file to open for output, must not benull- Returns:
- a new
FileOutputStreamfor the specified file - Throws:
java.lang.NullPointerException- if the file object isnull.java.lang.IllegalArgumentException- if the file object is a directoryjava.lang.IllegalArgumentException- if the file is not writable.java.io.IOException- if the directories could not be created.- Since:
- 1.3
-
openOutputStream
public static java.io.FileOutputStream openOutputStream(java.io.File file, boolean append) throws java.io.IOExceptionOpens aFileOutputStreamfor the specified file, checking and creating the parent directory if it does not exist.At the end of the method either the stream will be successfully opened, or an exception will have been thrown.
The parent directory will be created if it does not exist. The file will be created if it does not exist. An exception is thrown if the file object exists but is a directory. An exception is thrown if the file exists but cannot be written to. An exception is thrown if the parent directory cannot be created.
- Parameters:
file- the file to open for output, must not benullappend- iftrue, then bytes will be added to the end of the file rather than overwriting- Returns:
- a new
FileOutputStreamfor the specified file - Throws:
java.lang.NullPointerException- if the file object isnull.java.lang.IllegalArgumentException- if the file object is a directoryjava.lang.IllegalArgumentException- if the file is not writable.java.io.IOException- if the directories could not be created.- Since:
- 2.1
-
readFileToByteArray
public static byte[] readFileToByteArray(java.io.File file) throws java.io.IOExceptionReads 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:
java.lang.NullPointerException- if file isnull.java.io.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.java.io.IOException- if an I/O error occurs.- Since:
- 1.1
-
readFileToString
@Deprecated public static java.lang.String readFileToString(java.io.File file) throws java.io.IOExceptionDeprecated.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:
java.lang.NullPointerException- if file isnull.java.io.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.java.io.IOException- if an I/O error occurs.- Since:
- 1.3.1
-
readFileToString
public static java.lang.String readFileToString(java.io.File file, java.nio.charset.Charset charsetName) throws java.io.IOExceptionReads the contents of a file into a String. The file is always closed.- Parameters:
file- the file to read, must not benullcharsetName- the name of the requested charset,nullmeans platform default- Returns:
- the file contents, never
null - Throws:
java.lang.NullPointerException- if file isnull.java.io.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.java.io.IOException- if an I/O error occurs.- Since:
- 2.3
-
readFileToString
public static java.lang.String readFileToString(java.io.File file, java.lang.String charsetName) throws java.io.IOExceptionReads the contents of a file into a String. The file is always closed.- Parameters:
file- the file to read, must not benullcharsetName- the name of the requested charset,nullmeans platform default- Returns:
- the file contents, never
null - Throws:
java.lang.NullPointerException- if file isnull.java.io.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.java.io.IOException- if an I/O error occurs.java.nio.charset.UnsupportedCharsetException- thrown instead of.UnsupportedEncodingExceptionin version 2.2 if the named charset is unavailable.- Since:
- 2.3
-
readLines
@Deprecated public static java.util.List<java.lang.String> readLines(java.io.File file) throws java.io.IOExceptionDeprecated.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:
java.lang.NullPointerException- if file isnull.java.io.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.java.io.IOException- if an I/O error occurs.- Since:
- 1.3
-
readLines
public static java.util.List<java.lang.String> readLines(java.io.File file, java.nio.charset.Charset charset) throws java.io.IOExceptionReads 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 benullcharset- the charset to use,nullmeans platform default- Returns:
- the list of Strings representing each line in the file, never
null - Throws:
java.lang.NullPointerException- if file isnull.java.io.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.java.io.IOException- if an I/O error occurs.- Since:
- 2.3
-
readLines
public static java.util.List<java.lang.String> readLines(java.io.File file, java.lang.String charsetName) throws java.io.IOExceptionReads 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 benullcharsetName- the name of the requested charset,nullmeans platform default- Returns:
- the list of Strings representing each line in the file, never
null - Throws:
java.lang.NullPointerException- if file isnull.java.io.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.java.io.IOException- if an I/O error occurs.java.nio.charset.UnsupportedCharsetException- thrown instead of.UnsupportedEncodingExceptionin version 2.2 if the named charset is unavailable.- Since:
- 1.1
-
sizeOf
public static long sizeOf(java.io.File file)
Returns the size of the specified file or directory. If the providedFileis a regular file, then the file's length is returned. If the argument is a directory, then the size of the directory is calculated recursively. If a directory or subdirectory is security restricted, its size will not be included.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:
java.lang.NullPointerException- if the file isnull.java.lang.IllegalArgumentException- if the file does not exist.- Since:
- 2.0
-
sizeOfAsBigInteger
public static java.math.BigInteger sizeOfAsBigInteger(java.io.File file)
Returns the size of the specified file or directory. If the providedFileis a regular file, then the file's length is returned. If the argument is a directory, then the size of the directory is calculated recursively. If a directory or subdirectory is security restricted, its size will not be included.- Parameters:
file- the regular file or directory to return the size of (must not benull).- Returns:
- the length of the file, or recursive size of the directory, provided (in bytes).
- Throws:
java.lang.NullPointerException- if the file isnull.java.lang.IllegalArgumentException- if the file does not exist.- Since:
- 2.4
-
sizeOfDirectory
public static long sizeOfDirectory(java.io.File directory)
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:
java.lang.NullPointerException- if the directory isnull.
-
sizeOfDirectoryAsBigInteger
public static java.math.BigInteger sizeOfDirectoryAsBigInteger(java.io.File directory)
Counts the size of a directory recursively (sum of the length of all files).- Parameters:
directory- directory to inspect, must not benull.- Returns:
- size of directory in bytes, 0 if directory is security restricted.
- Throws:
java.lang.NullPointerException- if the directory isnull.- Since:
- 2.4
-
streamFiles
public static java.util.stream.Stream<java.io.File> streamFiles(java.io.File directory, boolean recursive, java.lang.String... extensions) throws java.io.IOExceptionStreams 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:
java.io.IOException- if an I/O error is thrown when accessing the starting file.- Since:
- 2.9.0
-
toFile
public static java.io.File toFile(java.net.URL url)
Converts from aURLto aFile.From version 1.1 this method will decode the URL. Syntax such as
file:///my%20docs/file.txtwill be correctly decoded to/my docs/file.txt. Starting with version 1.5, this method uses UTF-8 to decode percent-encoded octets to characters. Additionally, malformed percent-encoded octets are handled leniently by passing them through literally.- Parameters:
url- the file URL to convert,nullreturnsnull- Returns:
- the equivalent
Fileobject, ornullif the URL's protocol is notfile
-
toFiles
public static java.io.File[] toFiles(java.net.URL... urls)
Converts each of an array ofURLto aFile.Returns an array of the same size as the input. If the input is
null, an empty array is returned. If the input containsnull, the output array containsnullat the same index.This method will decode the URL. Syntax such as
file:///my%20docs/file.txtwill be correctly decoded to/my docs/file.txt.- Parameters:
urls- the file URLs to convert,nullreturns empty array- Returns:
- a non-
nullarray of Files matching the input, with anullitem if there was anullat that index in the input array - Throws:
java.lang.IllegalArgumentException- if any file is not a URL filejava.lang.IllegalArgumentException- if any file is incorrectly encoded- Since:
- 1.1
-
touch
public static void touch(java.io.File file) throws java.io.IOExceptionImplements 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:
java.io.IOException- if an I/O problem occurs.java.io.IOException- if setting the last-modified time failed.
-
toURLs
public static java.net.URL[] toURLs(java.io.File... files) throws java.io.IOExceptionConverts each of an array ofFileto aURL.Returns an array of the same size as the input.
- Parameters:
files- the files to convert, must not benull- Returns:
- an array of URLs matching the input
- Throws:
java.io.IOException- if a file cannot be convertedjava.lang.NullPointerException- if the parameter is null
-
waitFor
public static boolean waitFor(java.io.File file, int seconds)Waits for NFS to propagate a file creation, imposing a timeout.This method repeatedly tests
File.exists()until it returns true up to the maximum time specified in seconds.- Parameters:
file- the file to check, must not benullseconds- the maximum time in seconds to wait- Returns:
- true if file exists
- Throws:
java.lang.NullPointerException- if the file isnull
-
write
@Deprecated public static void write(java.io.File file, java.lang.CharSequence data) throws java.io.IOExceptionDeprecated.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:
java.io.IOException- in case of an I/O error- Since:
- 2.0
-
write
@Deprecated public static void write(java.io.File file, java.lang.CharSequence data, boolean append) throws java.io.IOExceptionDeprecated.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:
java.io.IOException- in case of an I/O error- Since:
- 2.1
-
write
public static void write(java.io.File file, java.lang.CharSequence data, java.nio.charset.Charset charset) throws java.io.IOExceptionWrites 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,nullmeans platform default- Throws:
java.io.IOException- in case of an I/O error- Since:
- 2.3
-
write
public static void write(java.io.File file, java.lang.CharSequence data, java.nio.charset.Charset charset, boolean append) throws java.io.IOExceptionWrites 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,nullmeans platform defaultappend- iftrue, then the data will be added to the end of the file rather than overwriting- Throws:
java.io.IOException- in case of an I/O error- Since:
- 2.3
-
write
public static void write(java.io.File file, java.lang.CharSequence data, java.lang.String charsetName) throws java.io.IOExceptionWrites 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,nullmeans platform default- Throws:
java.io.IOException- in case of an I/O errorjava.io.UnsupportedEncodingException- if the encoding is not supported by the VM- Since:
- 2.0
-
write
public static void write(java.io.File file, java.lang.CharSequence data, java.lang.String charsetName, boolean append) throws java.io.IOExceptionWrites 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,nullmeans platform defaultappend- iftrue, then the data will be added to the end of the file rather than overwriting- Throws:
java.io.IOException- in case of an I/O errorjava.nio.charset.UnsupportedCharsetException- thrown instead of.UnsupportedEncodingExceptionin version 2.2 if the encoding is not supported by the VM- Since:
- 2.1
-
writeByteArrayToFile
public static void writeByteArrayToFile(java.io.File file, byte[] data) throws java.io.IOExceptionWrites 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:
java.io.IOException- in case of an I/O error- Since:
- 1.1
-
writeByteArrayToFile
public static void writeByteArrayToFile(java.io.File file, byte[] data, boolean append) throws java.io.IOExceptionWrites 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:
java.io.IOException- in case of an I/O error- Since:
- 2.1
-
writeByteArrayToFile
public static void writeByteArrayToFile(java.io.File file, byte[] data, int off, int len) throws java.io.IOExceptionWriteslenbytes from the specified byte array starting at offsetoffto 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:
java.io.IOException- in case of an I/O error- Since:
- 2.5
-
writeByteArrayToFile
public static void writeByteArrayToFile(java.io.File file, byte[] data, int off, int len, boolean append) throws java.io.IOExceptionWriteslenbytes from the specified byte array starting at offsetoffto 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:
java.io.IOException- in case of an I/O error- Since:
- 2.5
-
writeLines
public static void writeLines(java.io.File file, java.util.Collection<?> lines) throws java.io.IOExceptionWrites thetoString()value of each item in a collection to the specifiedFileline by line. The default VM encoding and the default line ending will be used.- Parameters:
file- the file to write tolines- the lines to write,nullentries produce blank lines- Throws:
java.io.IOException- in case of an I/O error- Since:
- 1.3
-
writeLines
public static void writeLines(java.io.File file, java.util.Collection<?> lines, boolean append) throws java.io.IOExceptionWrites thetoString()value of each item in a collection to the specifiedFileline by line. The default VM encoding and the default line ending will be used.- Parameters:
file- the file to write tolines- the lines to write,nullentries produce blank linesappend- iftrue, then the lines will be added to the end of the file rather than overwriting- Throws:
java.io.IOException- in case of an I/O error- Since:
- 2.1
-
writeLines
public static void writeLines(java.io.File file, java.util.Collection<?> lines, java.lang.String lineEnding) throws java.io.IOExceptionWrites thetoString()value of each item in a collection to the specifiedFileline by line. The default VM encoding and the specified line ending will be used.- Parameters:
file- the file to write tolines- the lines to write,nullentries produce blank lineslineEnding- the line separator to use,nullis system default- Throws:
java.io.IOException- in case of an I/O error- Since:
- 1.3
-
writeLines
public static void writeLines(java.io.File file, java.util.Collection<?> lines, java.lang.String lineEnding, boolean append) throws java.io.IOExceptionWrites thetoString()value of each item in a collection to the specifiedFileline by line. The default VM encoding and the specified line ending will be used.- Parameters:
file- the file to write tolines- the lines to write,nullentries produce blank lineslineEnding- the line separator to use,nullis system defaultappend- iftrue, then the lines will be added to the end of the file rather than overwriting- Throws:
java.io.IOException- in case of an I/O error- Since:
- 2.1
-
writeLines
public static void writeLines(java.io.File file, java.lang.String charsetName, java.util.Collection<?> lines) throws java.io.IOExceptionWrites thetoString()value of each item in a collection to the specifiedFileline by line. The specified character encoding and the default line ending will be used.NOTE: As from v1.3, the parent directories of the file will be created if they do not exist.
- Parameters:
file- the file to write tocharsetName- the name of the requested charset,nullmeans platform defaultlines- the lines to write,nullentries produce blank lines- Throws:
java.io.IOException- in case of an I/O errorjava.io.UnsupportedEncodingException- if the encoding is not supported by the VM- Since:
- 1.1
-
writeLines
public static void writeLines(java.io.File file, java.lang.String charsetName, java.util.Collection<?> lines, boolean append) throws java.io.IOExceptionWrites thetoString()value of each item in a collection to the specifiedFileline by line, optionally appending. The specified character encoding and the default line ending will be used.- Parameters:
file- the file to write tocharsetName- the name of the requested charset,nullmeans platform defaultlines- the lines to write,nullentries produce blank linesappend- iftrue, then the lines will be added to the end of the file rather than overwriting- Throws:
java.io.IOException- in case of an I/O errorjava.io.UnsupportedEncodingException- if the encoding is not supported by the VM- Since:
- 2.1
-
writeLines
public static void writeLines(java.io.File file, java.lang.String charsetName, java.util.Collection<?> lines, java.lang.String lineEnding) throws java.io.IOExceptionWrites thetoString()value of each item in a collection to the specifiedFileline by line. The specified character encoding and the line ending will be used.NOTE: As from v1.3, the parent directories of the file will be created if they do not exist.
- Parameters:
file- the file to write tocharsetName- the name of the requested charset,nullmeans platform defaultlines- the lines to write,nullentries produce blank lineslineEnding- the line separator to use,nullis system default- Throws:
java.io.IOException- in case of an I/O errorjava.io.UnsupportedEncodingException- if the encoding is not supported by the VM- Since:
- 1.1
-
writeLines
public static void writeLines(java.io.File file, java.lang.String charsetName, java.util.Collection<?> lines, java.lang.String lineEnding, boolean append) throws java.io.IOExceptionWrites thetoString()value of each item in a collection to the specifiedFileline by line. The specified character encoding and the line ending will be used.- Parameters:
file- the file to write tocharsetName- the name of the requested charset,nullmeans platform defaultlines- the lines to write,nullentries produce blank lineslineEnding- the line separator to use,nullis system defaultappend- iftrue, then the lines will be added to the end of the file rather than overwriting- Throws:
java.io.IOException- in case of an I/O errorjava.io.UnsupportedEncodingException- if the encoding is not supported by the VM- Since:
- 2.1
-
writeStringToFile
@Deprecated public static void writeStringToFile(java.io.File file, java.lang.String data) throws java.io.IOExceptionDeprecated.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:
java.io.IOException- in case of an I/O error
-
writeStringToFile
@Deprecated public static void writeStringToFile(java.io.File file, java.lang.String data, boolean append) throws java.io.IOExceptionDeprecated.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:
java.io.IOException- in case of an I/O error- Since:
- 2.1
-
writeStringToFile
public static void writeStringToFile(java.io.File file, java.lang.String data, java.nio.charset.Charset charset) throws java.io.IOExceptionWrites 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,nullmeans platform default- Throws:
java.io.IOException- in case of an I/O errorjava.io.UnsupportedEncodingException- if the encoding is not supported by the VM- Since:
- 2.4
-
writeStringToFile
public static void writeStringToFile(java.io.File file, java.lang.String data, java.nio.charset.Charset charset, boolean append) throws java.io.IOExceptionWrites 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,nullmeans platform defaultappend- iftrue, then the String will be added to the end of the file rather than overwriting- Throws:
java.io.IOException- in case of an I/O error- Since:
- 2.3
-
writeStringToFile
public static void writeStringToFile(java.io.File file, java.lang.String data, java.lang.String charsetName) throws java.io.IOExceptionWrites 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,nullmeans platform default- Throws:
java.io.IOException- in case of an I/O errorjava.io.UnsupportedEncodingException- if the encoding is not supported by the VM
-
writeStringToFile
public static void writeStringToFile(java.io.File file, java.lang.String data, java.lang.String charsetName, boolean append) throws java.io.IOExceptionWrites 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,nullmeans platform defaultappend- iftrue, then the String will be added to the end of the file rather than overwriting- Throws:
java.io.IOException- in case of an I/O errorjava.nio.charset.UnsupportedCharsetException- thrown instead of.UnsupportedEncodingExceptionin version 2.2 if the encoding is not supported by the VM- Since:
- 2.1
-
-