Class FileUtils
Facilities are provided in the following areas:
- writing to a file
- reading from a file
- make a directory including parent directories
- copying files and directories
- deleting files and directories
- converting to and from a URL
- listing files and directories by filter and extension
- comparing file content
- file last changed date
- calculating a checksum
Note that a specific charset should be specified whenever possible. Relying on the platform default means that the code is Locale-dependent. Only use the default if the files are known to always use the platform default.
 SecurityException are not documented in the Javadoc.
 
Provenance: Excalibur, Alexandria, Commons-Utils
- 
Field SummaryFieldsModifier and TypeFieldDescriptionstatic final File[]An empty array of typeFile.static final longThe number of bytes in an exabyte.static final BigIntegerThe number of bytes in an exabyte.static final longThe number of bytes in a gigabyte.static final BigIntegerThe number of bytes in a gigabyte.static final longThe number of bytes in a kilobyte.static final BigIntegerThe number of bytes in a kilobyte.static final longThe number of bytes in a megabyte.static final BigIntegerThe number of bytes in a megabyte.static final longThe number of bytes in a petabyte.static final BigIntegerThe number of bytes in a petabyte.static final longThe number of bytes in a terabyte.static final BigIntegerThe number of bytes in a terabyte.static final BigIntegerThe number of bytes in a yottabyte.static final BigIntegerThe number of bytes in a zettabyte.
- 
Constructor SummaryConstructors
- 
Method SummaryModifier and TypeMethodDescriptionstatic StringbyteCountToDisplaySize(long size) Returns a human-readable version of the file size, where the input represents a specific number of bytes.static StringbyteCountToDisplaySize(Number size) Returns a human-readable version of the file size, where the input represents a specific number of bytes.static StringReturns a human-readable version of the file size, where the input represents a specific number of bytes.static ChecksumComputes the checksum of a file using the specified checksum object.static longchecksumCRC32(File file) Computes the checksum of a file using the CRC32 checksum routine.static voidcleanDirectory(File directory) Cleans a directory without deleting it.static booleancontentEquals(File file1, File file2) Tests whether the contents of two files are equal.static booleancontentEqualsIgnoreEOL(File file1, File file2, String charsetName) Compares the contents of two files to determine if they are equal or not.static File[]Converts a Collection containingFileinstances into array representation.static voidcopyDirectory(File srcDir, File destDir) Copies a whole directory to a new location, preserving the file dates.static voidcopyDirectory(File srcDir, File destDir, boolean preserveFileDate) Copies a whole directory to a new location.static voidcopyDirectory(File srcDir, File destDir, FileFilter filter) Copies a filtered directory to a new location preserving the file dates.static voidcopyDirectory(File srcDir, File destDir, FileFilter filter, boolean preserveFileDate) Copies a filtered directory to a new location.static voidcopyDirectory(File srcDir, File destDir, FileFilter fileFilter, boolean preserveFileDate, CopyOption... copyOptions) Copies a filtered directory to a new location.static voidcopyDirectoryToDirectory(File sourceDir, File destinationDir) Copies a directory to within another directory preserving the file dates.static voidCopies a file to a new location preserving the file date.static voidCopies an existing file to a new file location.static voidcopyFile(File srcFile, File destFile, boolean preserveFileDate, CopyOption... copyOptions) Copies the contents of a file to a new location.static voidcopyFile(File srcFile, File destFile, CopyOption... copyOptions) Copies a file to a new location.static longcopyFile(File input, OutputStream output) Copies bytes from aFileto anOutputStream.static voidcopyFileToDirectory(File srcFile, File destDir) Copies a file to a directory preserving the file date.static voidcopyFileToDirectory(File sourceFile, File destinationDir, boolean preserveFileDate) Copies a file to a directory optionally preserving the file date.static voidcopyInputStreamToFile(InputStream source, File destination) static voidcopyToDirectory(File sourceFile, File destinationDir) Copies a file or directory to within another directory preserving the file dates.static voidcopyToDirectory(Iterable<File> sourceIterable, File destinationDir) Copies a files to a directory preserving each file's date.static voidcopyToFile(InputStream inputStream, File file) Copies bytes from anInputStreamsource to aFiledestination.static voidcopyURLToFile(URL source, File destination) Copies bytes from the URLsourceto a filedestination.static voidcopyURLToFile(URL source, File destination, int connectionTimeoutMillis, int readTimeoutMillis) Copies bytes from the URLsourceto a filedestination.static FilecreateParentDirectories(File file) Creates all parent directories for a File object, including any necessary but non-existent parent directories.static Filecurrent()Gets the current directory.static FileDeletes the given File but throws an IOException if it cannot, unlikeFile.delete()which returns a boolean.static voiddeleteDirectory(File directory) Deletes a directory recursively.static booleandeleteQuietly(File file) Deletes a file, never throwing an exception.static booleandirectoryContains(File directory, File child) Tests whether theparentdirectory contains thechildelement (a file or directory).static voidforceDelete(File file) Deletes a file or directory.static voidforceDeleteOnExit(File file) Requests a file to be deleted when the virtual machine terminates.static voidforceMkdir(File directory) Creates all directories for a File object, including any necessary but non-existent parent directories.static voidforceMkdirParent(File file) Creates all directories for a File object, including any necessary but non-existent parent directories.static FileConstructs a file from the set of name elements.static FileConstructs a file from the set of name elements.static FileGets aFilerepresenting the system temporary directory.static StringGetsv the path to the system temporary directory.static FileGets aFilerepresenting the user's home directory.static StringGets the path to the user's home directory.static booleanisDirectory(File file, LinkOption... options) Tests whether the specifiedFileis a directory or not.static booleanisEmptyDirectory(File directory) Tests whether the directory is empty.static booleanisFileNewer(File file, long timeMillis) Tests if the specifiedFileis newer than the specified time reference.static booleanisFileNewer(File file, File reference) static booleanisFileNewer(File file, FileTime fileTime) static booleanisFileNewer(File file, ChronoLocalDate chronoLocalDate) Tests if the specifiedFileis newer than the specifiedChronoLocalDateat the end of day.static booleanisFileNewer(File file, ChronoLocalDate chronoLocalDate, LocalTime localTime) Tests if the specifiedFileis newer than the specifiedChronoLocalDateat the specified time.static booleanisFileNewer(File file, ChronoLocalDate chronoLocalDate, OffsetTime offsetTime) Tests if the specifiedFileis newer than the specifiedChronoLocalDateat the specifiedOffsetTime.static booleanisFileNewer(File file, ChronoLocalDateTime<?> chronoLocalDateTime) Tests if the specifiedFileis newer than the specifiedChronoLocalDateTimeat the system-default time zone.static booleanisFileNewer(File file, ChronoLocalDateTime<?> chronoLocalDateTime, ZoneId zoneId) Tests if the specifiedFileis newer than the specifiedChronoLocalDateTimeat the specifiedZoneId.static booleanisFileNewer(File file, ChronoZonedDateTime<?> chronoZonedDateTime) Tests if the specifiedFileis newer than the specifiedChronoZonedDateTime.static booleanisFileNewer(File file, Instant instant) static booleanisFileNewer(File file, OffsetDateTime offsetDateTime) Tests if the specifiedFileis newer than the specifiedOffsetDateTime.static booleanisFileNewer(File file, Date date) static booleanisFileOlder(File file, long timeMillis) Tests if the specifiedFileis older than the specified time reference.static booleanisFileOlder(File file, File reference) static booleanisFileOlder(File file, FileTime fileTime) static booleanisFileOlder(File file, ChronoLocalDate chronoLocalDate) Tests if the specifiedFileis older than the specifiedChronoLocalDateat the end of day.static booleanisFileOlder(File file, ChronoLocalDate chronoLocalDate, LocalTime localTime) static booleanisFileOlder(File file, ChronoLocalDate chronoLocalDate, OffsetTime offsetTime) Tests if the specifiedFileis older than the specifiedChronoLocalDateat the specifiedOffsetTime.static booleanisFileOlder(File file, ChronoLocalDateTime<?> chronoLocalDateTime) Tests if the specifiedFileis older than the specifiedChronoLocalDateTimeat the system-default time zone.static booleanisFileOlder(File file, ChronoLocalDateTime<?> chronoLocalDateTime, ZoneId zoneId) Tests if the specifiedFileis older than the specifiedChronoLocalDateTimeat the specifiedZoneId.static booleanisFileOlder(File file, ChronoZonedDateTime<?> chronoZonedDateTime) Tests if the specifiedFileis older than the specifiedChronoZonedDateTime.static booleanisFileOlder(File file, Instant instant) static booleanisFileOlder(File file, OffsetDateTime offsetDateTime) Tests if the specifiedFileis older than the specifiedOffsetDateTime.static booleanisFileOlder(File file, Date date) static booleanisRegularFile(File file, LinkOption... options) Tests whether the specifiedFileis a regular file or not.static booleanTests whether the specified file is a symbolic link rather than an actual file.iterateFiles(File directory, String[] extensions, boolean recursive) Iterates over the files in a given directory (and optionally its subdirectories) which match an array of extensions.iterateFiles(File directory, IOFileFilter fileFilter, IOFileFilter dirFilter) Iterates over the files in given directory (and optionally its subdirectories).iterateFilesAndDirs(File directory, IOFileFilter fileFilter, IOFileFilter dirFilter) Iterates over the files in given directory (and optionally its subdirectories).static longlastModified(File file) Returns the last modification time in milliseconds viaFiles.getLastModifiedTime(Path, LinkOption...).static FileTimelastModifiedFileTime(File file) Returns the last modificationFileTimeviaFiles.getLastModifiedTime(Path, LinkOption...).static longlastModifiedUnchecked(File file) Returns the last modification time in milliseconds viaFiles.getLastModifiedTime(Path, LinkOption...).static LineIteratorlineIterator(File file) Returns an Iterator for the lines in aFileusing the default encoding for the VM.static LineIteratorlineIterator(File file, String charsetName) Returns an Iterator for the lines in aFile.static Collection<File> Lists files within a given directory (and optionally its subdirectories) which match an array of extensions.static Collection<File> listFiles(File directory, IOFileFilter fileFilter, IOFileFilter dirFilter) Finds files within a given directory (and optionally its subdirectories).static Collection<File> listFilesAndDirs(File directory, IOFileFilter fileFilter, IOFileFilter dirFilter) Finds files within a given directory (and optionally its subdirectories).static voidmoveDirectory(File srcDir, File destDir) Moves a directory.static voidmoveDirectoryToDirectory(File source, File destDir, boolean createDestDir) Moves a directory to another directory.static voidMoves a file preserving attributes.static voidmoveFile(File srcFile, File destFile, CopyOption... copyOptions) Moves a file.static voidmoveFileToDirectory(File srcFile, File destDir, boolean createDestDir) Moves a file into a directory.static voidmoveToDirectory(File src, File destDir, boolean createDestDir) Moves a file or directory into a destination directory.static OutputStreamnewOutputStream(File file, boolean append) Creates a new OutputStream by opening or creating a file, returning an output stream that may be used to write bytes to the file.static FileInputStreamopenInputStream(File file) Opens aFileInputStreamfor the specified file, providing better error messages than simply callingnew FileInputStream(file).static FileOutputStreamopenOutputStream(File file) Opens aFileOutputStreamfor the specified file, checking and creating the parent directory if it does not exist.static FileOutputStreamopenOutputStream(File file, boolean append) Opens aFileOutputStreamfor the specified file, checking and creating the parent directory if it does not exist.static byte[]readFileToByteArray(File file) Reads the contents of a file into a byte array.static StringreadFileToString(File file) Deprecated.UsereadFileToString(File, Charset)instead (and specify the appropriate encoding)static StringreadFileToString(File file, String charsetName) Reads the contents of a file into a String.static StringreadFileToString(File file, Charset charsetName) Reads the contents of a file into a String.Deprecated.UsereadLines(File, Charset)instead (and specify the appropriate encoding)Reads the contents of a file line by line to a List of Strings.Reads the contents of a file line by line to a List of Strings.static longReturns the size of the specified file or directory.static BigIntegersizeOfAsBigInteger(File file) Returns the size of the specified file or directory.static longsizeOfDirectory(File directory) Counts the size of a directory recursively (sum of the length of all files).static BigIntegersizeOfDirectoryAsBigInteger(File directory) Counts the size of a directory recursively (sum of the length of all files).streamFiles(File directory, boolean recursive, String... extensions) Streams over the files in a given directory (and optionally its subdirectories) which match an array of extensions.static Filestatic File[]static voidImplements behavior similar to the Unix "touch" utility.static URL[]static booleanWaits for the file system to detect a file's presence, with a timeout.static voidwrite(File file, CharSequence data) Deprecated.Usewrite(File, CharSequence, Charset)instead (and specify the appropriate encoding)static voidwrite(File file, CharSequence data, boolean append) Deprecated.Usewrite(File, CharSequence, Charset, boolean)instead (and specify the appropriate encoding)static voidwrite(File file, CharSequence data, String charsetName) Writes a CharSequence to a file creating the file if it does not exist.static voidwrite(File file, CharSequence data, String charsetName, boolean append) Writes a CharSequence to a file creating the file if it does not exist.static voidwrite(File file, CharSequence data, Charset charset) Writes a CharSequence to a file creating the file if it does not exist.static voidwrite(File file, CharSequence data, Charset charset, boolean append) Writes a CharSequence to a file creating the file if it does not exist.static voidwriteByteArrayToFile(File file, byte[] data) Writes a byte array to a file creating the file if it does not exist.static voidwriteByteArrayToFile(File file, byte[] data, boolean append) Writes a byte array to a file creating the file if it does not exist.static voidwriteByteArrayToFile(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(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(File file, String charsetName, Collection<?> lines) Writes thetoString()value of each item in a collection to the specifiedFileline by line.static voidwriteLines(File file, String charsetName, Collection<?> lines, boolean append) Writes thetoString()value of each item in a collection to the specifiedFileline by line, optionally appending.static voidwriteLines(File file, String charsetName, Collection<?> lines, String lineEnding) Writes thetoString()value of each item in a collection to the specifiedFileline by line.static voidwriteLines(File file, String charsetName, Collection<?> lines, String lineEnding, boolean append) Writes thetoString()value of each item in a collection to the specifiedFileline by line.static voidwriteLines(File file, Collection<?> lines) Writes thetoString()value of each item in a collection to the specifiedFileline by line.static voidwriteLines(File file, Collection<?> lines, boolean append) Writes thetoString()value of each item in a collection to the specifiedFileline by line.static voidwriteLines(File file, Collection<?> lines, String lineEnding) Writes thetoString()value of each item in a collection to the specifiedFileline by line.static voidwriteLines(File file, Collection<?> lines, String lineEnding, boolean append) Writes thetoString()value of each item in a collection to the specifiedFileline by line.static voidwriteStringToFile(File file, String data) Deprecated.UsewriteStringToFile(File, String, Charset)instead (and specify the appropriate encoding)static voidwriteStringToFile(File file, String data, boolean append) Deprecated.UsewriteStringToFile(File, String, Charset, boolean)instead (and specify the appropriate encoding)static voidwriteStringToFile(File file, String data, String charsetName) Writes a String to a file, creating the file if it does not exist.static voidwriteStringToFile(File file, String data, String charsetName, boolean append) Writes a String to a file, creating the file if it does not exist.static voidwriteStringToFile(File file, String data, Charset charset) Writes a String to a file creating the file if it does not exist.static voidwriteStringToFile(File file, String data, Charset charset, boolean append) Writes a String to a file, creating the file if it does not exist.
- 
Field Details- 
ONE_KBThe number of bytes in a kilobyte.- See Also:
 
- 
ONE_KB_BIThe number of bytes in a kilobyte.- Since:
- 2.4
 
- 
ONE_MBThe number of bytes in a megabyte.- See Also:
 
- 
ONE_MB_BIThe number of bytes in a megabyte.- Since:
- 2.4
 
- 
ONE_GBThe number of bytes in a gigabyte.- See Also:
 
- 
ONE_GB_BIThe number of bytes in a gigabyte.- Since:
- 2.4
 
- 
ONE_TBThe number of bytes in a terabyte.- See Also:
 
- 
ONE_TB_BIThe number of bytes in a terabyte.- Since:
- 2.4
 
- 
ONE_PBThe number of bytes in a petabyte.- See Also:
 
- 
ONE_PB_BIThe number of bytes in a petabyte.- Since:
- 2.4
 
- 
ONE_EBThe number of bytes in an exabyte.- See Also:
 
- 
ONE_EB_BIThe number of bytes in an exabyte.- Since:
- 2.4
 
- 
ONE_ZBThe number of bytes in a zettabyte.
- 
ONE_YBThe number of bytes in a yottabyte.
- 
EMPTY_FILE_ARRAYAn empty array of typeFile.
 
- 
- 
Constructor Details- 
FileUtilsDeprecated.TODO Make private in 3.0.Instances should NOT be constructed in standard programming.
 
- 
- 
Method Details- 
byteCountToDisplaySizeReturns 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, the size is rounded down to the nearest GB boundary. Similarly for the 1MB and 1KB boundaries. - Parameters:
- size- the number of bytes
- Returns:
- a human-readable display value (includes units - EB, PB, TB, GB, MB, KB or bytes)
- Throws:
- NullPointerException- if the given- BigIntegeris- null.
- Since:
- 2.4
- See Also:
 
- 
byteCountToDisplaySizeReturns 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, 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:
 
- 
byteCountToDisplaySizeReturns 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, the size is rounded down to the nearest GB boundary. Similarly for the 1MB and 1KB boundaries. - Parameters:
- size- the number of bytes
- Returns:
- a human-readable display value (includes units - EB, PB, TB, GB, MB, KB or bytes)
- Since:
- 2.12.0
- See Also:
 
- 
checksumComputes 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 be- null
- checksum- the checksum object to be used, must not be- null
- Returns:
- the checksum specified, updated with the content of the file
- Throws:
- NullPointerException- if the given- Fileis- null.
- NullPointerException- if the given- Checksumis- null.
- IllegalArgumentException- if the given- Fileis not a file.
- FileNotFoundException- if the file does not exist
- IOException- if an IO error occurs reading the file.
- Since:
- 1.3
 
- 
checksumCRC32Computes 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 be- null
- Returns:
- the checksum value
- Throws:
- NullPointerException- if the- fileis- null.
- IllegalArgumentException- if the- filedoes not exist or is not a file.
- IOException- if an IO error occurs reading the file.
- Since:
- 1.3
 
- 
cleanDirectoryCleans a directory without deleting it.- Parameters:
- directory- directory to clean
- Throws:
- NullPointerException- if the given- Fileis- null.
- IllegalArgumentException- if the- directorydoes not exist or is not a directory.
- IOException- if an I/O error occurs.
- See Also:
 
- 
contentEqualsTests 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. - Parameters:
- file1- the first file
- file2- the second file
- Returns:
- true if the content of the files are equal or they both don't exist, false otherwise
- Throws:
- IllegalArgumentException- when an input is not a file.
- IOException- If an I/O error occurs.
- See Also:
 
- 
contentEqualsIgnoreEOLpublic static boolean contentEqualsIgnoreEOL(File file1, File file2, String charsetName) throws IOException Compares the contents of two files to determine if they are equal or not.This method checks to see if the two files point to the same file, before resorting to line-by-line comparison of the contents. - Parameters:
- file1- the first file
- file2- the second file
- charsetName- the name of the requested charset. May be null, in which case the platform default is used
- Returns:
- true if the content of the files are equal or neither exists, false otherwise
- Throws:
- IllegalArgumentException- when an input is not a file.
- IOException- in case of an I/O error.
- UnsupportedCharsetException- If the named charset is unavailable (unchecked exception).
- Since:
- 2.2
- See Also:
 
- 
convertFileCollectionToFileArrayConverts a Collection containingFileinstances into array representation. This is to account for the difference between File.listFiles() and FileUtils.listFiles().
- 
copyDirectoryCopies 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. That is, copying /home/bar to /tmp/bang copies the contents of /home/bar into /tmp/bang. It does not create /tmp/bang/bar. The destination directory is created if it does not exist. If the destination directory does exist, then this method merges the source with the destination, with the source taking precedence. Note: This method tries to preserve the file's last modified date/times using BasicFileAttributeView.setTimes(FileTime, FileTime, FileTime). However it is not guaranteed that the operation will succeed. If the modification operation fails, it falls back toFile.setLastModified(long). If that fails, the method throws IOException.Symbolic links in the source directory are copied to new symbolic links in the destination directory that point to the original target. The target of the link is not copied unless it is also under the source directory. Even if it is under the source directory, the new symbolic link in the destination points to the original target in the source directory, not to the newly created copy of the target. - Parameters:
- srcDir- an existing directory to copy, must not be- null.
- destDir- the new directory, must not be- null.
- Throws:
- NullPointerException- if any of the given- Files are- null.
- IllegalArgumentException- if- srcDirexists but is not a directory, the source and the destination directory are the same
- FileNotFoundException- if the source does not exist.
- IOException- if an error occurs, the destination is not writable, or setting the last-modified time didn't succeed
- Since:
- 1.1
 
- 
copyDirectorypublic static void copyDirectory(File srcDir, File destDir, boolean preserveFileDate) throws IOException Copies a whole directory to a new location.This method copies the contents of the specified source directory to within the specified destination directory. The destination directory is created if it does not exist. If the destination directory does 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 method throws IOException.- Parameters:
- srcDir- an existing directory to copy, must not be- null.
- destDir- the new directory, must not be- null.
- preserveFileDate- true if the file date of the copy should be the same as the original.
- Throws:
- IllegalArgumentException- if- srcDirexists but is not a directory, or the source and the destination directory are the same
- FileNotFoundException- if the source does not exist.
- IOException- if an error occurs, the destination is not writable, or setting the last-modified time didn't succeed
- Since:
- 1.1
 
- 
copyDirectoryCopies 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 does 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 method 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.INSTANCE, 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 be- null.
- destDir- the new directory, must not be- null.
- filter- the filter to apply, null means copy all directories and files should be the same as the original.
- Throws:
- NullPointerException- if any of the given- Files are- null.
- IllegalArgumentException- if- srcDirexists but is not a directory, or the source and the destination directory are the same
- FileNotFoundException- if the source does not exist.
- IOException- if an error occurs, the destination is not writable, or setting the last-modified time didn't succeed
- Since:
- 1.4
 
- 
copyDirectorypublic static void copyDirectory(File srcDir, File destDir, FileFilter filter, boolean preserveFileDate) throws IOException Copies a filtered directory to a new location.This method copies the contents of the specified source directory to within the specified destination directory. The destination directory is created if it does not exist. If the destination directory does exist, then this method merges the source with the destination, with the source taking precedence. Note: Setting Example: Copy directories onlypreserveFileDatetotruetries to preserve the file's last modified date/times usingBasicFileAttributeView.setTimes(FileTime, FileTime, FileTime). However, it is not guaranteed that the operation will succeed. If the modification operation fails it falls back toFile.setLastModified(long). If that fails, the method 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.INSTANCE, 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 be- null.
- destDir- the new directory, must not be- null.
- filter- the filter to apply, null means copy all directories and files.
- preserveFileDate- true if the file date of the copy should be the same as the original.
- Throws:
- NullPointerException- if any of the given- Files are- null.
- IllegalArgumentException- if- srcDirexists but is not a directory, the source and the destination directory are the same, or the destination is not writable
- FileNotFoundException- if the source does not exist.
- IOException- if an error occurs or setting the last-modified time didn't succeed.
- Since:
- 1.4
 
- 
copyDirectorypublic static void copyDirectory(File srcDir, File destDir, FileFilter fileFilter, boolean preserveFileDate, CopyOption... copyOptions) throws IOException Copies a filtered directory to a new location.This method copies the contents of the specified source directory to within the specified destination directory. The destination directory is created if it does not exist. If the destination directory does exist, then this method merges the source with the destination, with the source taking precedence. Note: Setting Example: Copy directories onlypreserveFileDatetotruetries to preserve the file's last modified date/times usingBasicFileAttributeView.setTimes(FileTime, FileTime, FileTime). However, it is not guaranteed that the operation will succeed. If the modification operation fails it falls back toFile.setLastModified(long). If that fails, the method 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.INSTANCE, 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 be- null
- destDir- the new directory, must not be- null
- fileFilter- 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
- copyOptions- options specifying how the copy should be done, for example- StandardCopyOption.
- Throws:
- NullPointerException- if any of the given- Files are- null.
- IllegalArgumentException- if- srcDirexists but is not a directory, or the source and the destination directory are the same
- FileNotFoundException- if the source does not exist.
- IOException- if an error occurs, the destination is not writable, or setting the last-modified time didn't succeed
- Since:
- 2.8.0
 
- 
copyDirectoryToDirectoryCopies 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 does exist, then this method merges the source with the destination, with the source taking precedence. Note: Setting preserveFileDatetotruetries to preserve the file's last modified date/times usingBasicFileAttributeView.setTimes(FileTime, FileTime, FileTime). However, it is not guaranteed that the operation will succeed. If the modification operation fails it falls back toFile.setLastModified(long)and if that fails, the method throws IOException.- Parameters:
- sourceDir- an existing directory to copy, must not be- null.
- destinationDir- the directory to place the copy in, must not be- null.
- Throws:
- NullPointerException- if any of the given- Files are- null.
- IllegalArgumentException- if the source or destination is invalid.
- FileNotFoundException- if the source does not exist.
- IOException- if an error occurs, the destination is not writable, or setting the last-modified time didn't succeed
- Since:
- 1.2
 
- 
copyFileCopies 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 overwrites it. A symbolic link is resolved before copying so the new file is not a link. Note: This method tries to preserve the file's last modified date/times using BasicFileAttributeView.setTimes(FileTime, FileTime, FileTime). However, it is not guaranteed that the operation will succeed. If the modification operation fails, it falls back toFile.setLastModified(long), and if that fails, the method throws IOException.- Parameters:
- srcFile- an existing file to copy, must not be- null.
- destFile- the new file, must not be- null.
- Throws:
- NullPointerException- if any of the given- Files are- null.
- IOException- if source or destination is invalid.
- IOException- if an error occurs or setting the last-modified time didn't succeed.
- IOException- if the output file length is not the same as the input file length after the copy completes.
- See Also:
 
- 
copyFilepublic static void copyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException Copies an existing file to a new file location.This method copies the contents of the specified source file to the specified destination file. The directory holding the destination file is created if it does not exist. If the destination file exists, then this method overwrites it. A symbolic link is resolved before copying so the new file is not a link. Note: Setting preserveFileDatetotruetries to preserve the file's last modified date/times usingBasicFileAttributeView.setTimes(FileTime, FileTime, FileTime). However, it is not guaranteed that the operation will succeed. If the modification operation fails, it falls back toFile.setLastModified(long), and if that fails, the method throws IOException.- Parameters:
- srcFile- an existing file to copy, must not be- null.
- destFile- the new file, must not be- null.
- preserveFileDate- true if the file date of the copy should be the same as the original.
- Throws:
- NullPointerException- if any of the given- Files are- null.
- IOException- if source or destination is invalid.
- IOException- if an error occurs or setting the last-modified time didn't succeed.
- IOException- if the output file length is not the same as the input file length after the copy completes
- See Also:
 
- 
copyFilepublic static void copyFile(File srcFile, File destFile, boolean preserveFileDate, CopyOption... copyOptions) throws IOException Copies the contents of 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.By default, a symbolic link is resolved before copying so the new file is not a link. To copy symbolic links as links, you can pass LinkOption.NO_FOLLOW_LINKSas the last argument.Note: Setting preserveFileDatetotruetries to preserve the file's last modified date/times usingBasicFileAttributeView.setTimes(FileTime, FileTime, FileTime). However, it is not guaranteed that the operation will succeed. If the modification operation fails, it falls back toFile.setLastModified(long), and if that fails, the method throws IOException.- Parameters:
- srcFile- an existing file to copy, must not be- null.
- destFile- the new file, must not be- null.
- 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 example- StandardCopyOption.
- Throws:
- NullPointerException- if any of the given- Files are- null.
- FileNotFoundException- if the source does not exist.
- IllegalArgumentException- if- srcFileor- destFileis not a file
- IOException- if the output file length is not the same as the input file length after the copy completes.
- IOException- if an I/O error occurs, setting the last-modified time didn't succeed, or the destination is not writable
- Since:
- 2.8.0
- See Also:
 
- 
copyFilepublic static void copyFile(File srcFile, File destFile, CopyOption... copyOptions) throws IOException Copies a file to a new location.This method copies the contents of the specified source file to the specified destination file. The directory holding the destination file is created if it does not exist. If the destination file exists, you can overwrite it if you use StandardCopyOption.REPLACE_EXISTING.- Parameters:
- srcFile- an existing file to copy, must not be- null.
- destFile- the new file, must not be- null.
- copyOptions- options specifying how the copy should be done, for example- StandardCopyOption.
- Throws:
- NullPointerException- if any of the given- Files are- null.
- FileNotFoundException- if the source does not exist.
- IllegalArgumentException- if source is not a file.
- IOException- if an I/O error occurs.
- Since:
- 2.9.0
- See Also:
 
- 
copyFileCopies bytes from aFileto anOutputStream.This method buffers the input internally, so there is no need to use a BufferedInputStream.- Parameters:
- input- the- Fileto read.
- output- the- OutputStreamto write.
- Returns:
- the number of bytes copied
- Throws:
- NullPointerException- if the File is- null.
- NullPointerException- if the OutputStream is- null.
- IOException- if an I/O error occurs.
- Since:
- 2.1
 
- 
copyFileToDirectoryCopies 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 BasicFileAttributeView.setTimes(FileTime, FileTime, FileTime). However, it is not guaranteed that the operation will succeed. If the modification operation fails it falls back toFile.setLastModified(long)and if that fails, the method throws IOException.- Parameters:
- srcFile- an existing file to copy, must not be- null.
- destDir- the directory to place the copy in, must not be- null.
- Throws:
- NullPointerException- if any of the given- Files are- null.
- IllegalArgumentException- if source or destination is invalid.
- IOException- if an error occurs or setting the last-modified time didn't succeed.
- See Also:
 
- 
copyFileToDirectorypublic static void copyFileToDirectory(File sourceFile, File destinationDir, boolean preserveFileDate) throws IOException Copies a file to a directory optionally preserving the file date.This method copies the contents of the specified source file to a file of the same name in the specified destination directory. The destination directory is created if it does not exist. If the destination file exists, then this method will overwrite it. Note: Setting preserveFileDatetotruetries to preserve the file's last modified date/times usingBasicFileAttributeView.setTimes(FileTime, FileTime, FileTime). However, it is not guaranteed that the operation will succeed. If the modification operation fails it falls back toFile.setLastModified(long)and if that fails, the method throws IOException.- Parameters:
- sourceFile- an existing file to copy, must not be- null.
- destinationDir- the directory to place the copy in, must not be- null.
- preserveFileDate- true if the file date of the copy should be the same as the original.
- Throws:
- NullPointerException- if any of the given- Files are- null.
- IOException- if an error occurs or setting the last-modified time didn't succeed.
- IOException- if the output file length is not the same as the input file length after the copy completes.
- Since:
- 1.3
- See Also:
 
- 
copyInputStreamToFileCopies 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- the- InputStreamto copy bytes from, must not be- null, will be closed
- destination- the non-directory- Fileto write bytes to (possibly overwriting), must not be- null
- Throws:
- IOException- if- destinationis a directory
- IOException- if- destinationcannot be written
- IOException- if- destinationneeds creating but can't be
- IOException- if an IO error occurs during copying
- Since:
- 2.0
 
- 
copyToDirectoryCopies a file or directory to within another directory preserving the file dates.This method copies the source file or directory, along with 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 does exist, then this method merges the source with the destination, with the source taking precedence. Note: Setting preserveFileDatetotruetries to preserve the file's last modified date/times usingBasicFileAttributeView.setTimes(FileTime, FileTime, FileTime). However, it is not guaranteed that the operation will succeed. If the modification operation fails it falls back toFile.setLastModified(long)and if that fails, the method throws IOException.- Parameters:
- sourceFile- an existing file or directory to copy, must not be- null.
- destinationDir- the directory to place the copy in, must not be- null.
- Throws:
- NullPointerException- if any of the given- Files are- null.
- IllegalArgumentException- if the source or destination is invalid.
- FileNotFoundException- if the source does not exist.
- IOException- if an error occurs or setting the last-modified time didn't succeed.
- Since:
- 2.6
- See Also:
 
- 
copyToDirectorypublic static void copyToDirectory(Iterable<File> sourceIterable, File destinationDir) throws IOException Copies a files to a directory preserving each file's date.This method copies the contents of the specified source files to a file of the same name in the specified destination directory. The destination directory is created if it does not exist. If the destination file exists, then this method will overwrite it. Note: This method tries to preserve the file's last modified date/times using BasicFileAttributeView.setTimes(FileTime, FileTime, FileTime). However, it is not guaranteed that the operation will succeed. If the modification operation fails it falls back toFile.setLastModified(long)and if that fails, the method throws IOException.- Parameters:
- sourceIterable- existing files to copy, must not be- null.
- destinationDir- the directory to place the copies in, must not be- null.
- Throws:
- NullPointerException- if any of the given- Files are- null.
- IOException- if source or destination is invalid.
- IOException- if an error occurs or setting the last-modified time didn't succeed.
- Since:
- 2.6
- See Also:
 
- 
copyToFileCopies 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- the- InputStreamto copy bytes from, must not be- null
- file- the non-directory- Fileto write bytes to (possibly overwriting), must not be- null
- Throws:
- NullPointerException- if the InputStream is- null.
- NullPointerException- if the File is- null.
- IllegalArgumentException- if the file object is a directory.
- IllegalArgumentException- if the file is not writable.
- IOException- if the directories could not be created.
- IOException- if an IO error occurs during copying.
- Since:
- 2.5
 
- 
copyURLToFileCopies 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- the- URLto copy bytes from, must not be- null
- destination- the non-directory- Fileto write bytes to (possibly overwriting), must not be- null
- Throws:
- IOException- if- sourceURL cannot be opened
- IOException- if- destinationis a directory
- IOException- if- destinationcannot be written
- IOException- if- destinationneeds creating but can't be
- IOException- if an IO error occurs during copying
 
- 
copyURLToFilepublic static void copyURLToFile(URL source, File destination, int connectionTimeoutMillis, int readTimeoutMillis) throws IOException Copies bytes from the URLsourceto a filedestination. The directories up todestinationwill be created if they don't already exist.destinationwill be overwritten if it already exists.- Parameters:
- source- the- URLto copy bytes from, must not be- null
- destination- the non-directory- Fileto write bytes to (possibly overwriting), must not be- null
- connectionTimeoutMillis- the number of milliseconds until this method will time out if no connection could be established to the- source
- readTimeoutMillis- the number of milliseconds until this method will time out if no data could be read from the- source
- Throws:
- IOException- if- sourceURL cannot be opened
- IOException- if- destinationis a directory
- IOException- if- destinationcannot be written
- IOException- if- destinationneeds creating but can't be
- IOException- if an IO error occurs during copying
- Since:
- 2.0
 
- 
createParentDirectoriesCreates all parent directories for a File object, including any necessary but non-existent parent directories. If a parent directory already exists or is null, nothing happens.- Parameters:
- file- the File that may need parents, may be null.
- Returns:
- The parent directory, or nullif the given File does have a parent.
- Throws:
- IOException- if the directory was not created along with all its parent directories.
- SecurityException- See- File.mkdirs().
- Since:
- 2.9.0
 
- 
currentGets the current directory.- Returns:
- the current directory.
- Since:
- 2.12.0
 
- 
deleteDeletes 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:
- NullPointerException- if the parameter is- null
- IOException- if the file cannot be deleted.
- Since:
- 2.9.0
- See Also:
 
- 
deleteDirectoryDeletes a directory recursively.- Parameters:
- directory- directory to delete
- Throws:
- IOException- in case deletion is unsuccessful
- NullPointerException- if the parameter is- null
- IllegalArgumentException- if- directoryis not a directory
 
- 
deleteQuietlyDeletes a file, never throwing an exception. If file is a directory, delete it and all subdirectories.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 be- null
- Returns:
- trueif the file or directory was deleted, otherwise- false
- Since:
- 1.4
 
- 
directoryContainsTests whether theparentdirectory contains thechildelement (a file or directory).Files are normalized before comparison. Edge cases:- A directorymust not be null: if null, throw NullPointerException
- A directorymust be a directory: if not a directory, throw IllegalArgumentException
- A directory does not contain itself: return false
- A null child file is not contained in any parent: return false
 - Parameters:
- directory- the file to consider as the parent.
- child- the file to consider as the child.
- Returns:
- true is the candidate leaf is under by the specified composite. False otherwise.
- Throws:
- IOException- if an IO error occurs while checking the files.
- NullPointerException- if the parent is- null.
- IllegalArgumentException- if the parent is not a directory.
- Since:
- 2.2
- See Also:
 
- A 
- 
forceDeleteDeletes a file or directory. For a directory, delete it and all subdirectories.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 be- null.
- Throws:
- NullPointerException- if the file is- null.
- FileNotFoundException- if the file was not found.
- IOException- in case deletion is unsuccessful.
 
- 
forceDeleteOnExitRequests a file to be deleted when the virtual machine terminates. If file is directory delete it and all subdirectories.- Parameters:
- file- file or directory to delete, must not be- null.
- Throws:
- NullPointerException- if the file is- null.
- IOException- in case deletion is unsuccessful.
 
- 
forceMkdirCreates all directories for a File object, including any necessary but non-existent parent directories. If thedirectoryalready exists or is null, nothing happens.Calls File.mkdirs()and throws anIOExceptionon failure.- Parameters:
- directory- the receiver for- mkdirs(). If the- directoryalready exists or is null, nothing happens.
- Throws:
- IOException- if the directory was not created along with all its parent directories.
- IOException- if the given file object is not a directory.
- SecurityException- See- File.mkdirs().
- See Also:
 
- 
forceMkdirParentCreates all directories for a File object, including any necessary but non-existent parent directories. If the parent directory already exists or is null, nothing happens.Calls File.mkdirs()for the parent offile.- Parameters:
- file- file with parents to create, must not be- null.
- Throws:
- NullPointerException- if the file is- null.
- IOException- if the directory was not created along with all its parent directories.
- SecurityException- See- File.mkdirs().
- Since:
- 2.5
- See Also:
 
- 
getFileConstructs a file from the set of name elements.- Parameters:
- directory- the parent directory.
- names- the name elements.
- Returns:
- the new file.
- Since:
- 2.1
 
- 
getFileConstructs a file from the set of name elements.- Parameters:
- names- the name elements.
- Returns:
- the file.
- Since:
- 2.1
 
- 
getTempDirectoryGets aFilerepresenting the system temporary directory.- Returns:
- the system temporary directory as a File
- Since:
- 2.0
 
- 
getTempDirectoryPathGetsv the path to the system temporary directory. WARNING: this method relies on the Java system property 'java.io.tmpdir' which may or may not have a trailing file separator. This can affect code that uses String processing to manipulate pathnames rather than the standard libary methods in classes such asFile- Returns:
- the path to the system temporary directory as a String
- Since:
- 2.0
 
- 
getUserDirectoryGets aFilerepresenting the user's home directory.- Returns:
- the user's home directory.
- Since:
- 2.0
 
- 
getUserDirectoryPathGets the path to the user's home directory.- Returns:
- the path to the user's home directory.
- Since:
- 2.0
 
- 
isDirectoryTests 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:
- SecurityException- In the case of the default provider, and a security manager is installed, the- checkReadmethod is invoked to check read access to the directory.
- Since:
- 2.9.0
 
- 
isEmptyDirectoryTests whether the directory is empty.- Parameters:
- directory- the directory to query.
- Returns:
- whether the directory is empty.
- Throws:
- IOException- if an I/O error occurs.
- NotDirectoryException- if the file could not otherwise be opened because it is not a directory (optional specific exception).
- Since:
- 2.9.0
 
- 
isFileNewerTests if the specifiedFileis newer than the specifiedChronoLocalDateat the end of day.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- the- Fileof 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:
- UncheckedIOException- if an I/O error occurs
- NullPointerException- if the file or local date is- null.
- Since:
- 2.8.0
 
- 
isFileNewerTests 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- the- Fileof 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:
- UncheckedIOException- if an I/O error occurs
- NullPointerException- if the file, local date or zone ID is- null.
- Since:
- 2.8.0
 
- 
isFileNewerpublic static boolean isFileNewer(File file, ChronoLocalDate chronoLocalDate, OffsetTime offsetTime) Tests if the specifiedFileis newer than the specifiedChronoLocalDateat the specifiedOffsetTime.- Parameters:
- file- the- Fileof which the modification date must be compared
- chronoLocalDate- the date reference
- offsetTime- the time reference
- Returns:
- true if the Fileexists and has been modified after the givenChronoLocalDateat the givenOffsetTime.
- Throws:
- UncheckedIOException- if an I/O error occurs
- NullPointerException- if the file, local date or zone ID is- null
- Since:
- 2.12.0
 
- 
isFileNewerTests 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- the- Fileof 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:
- UncheckedIOException- if an I/O error occurs
- NullPointerException- if the file or local date time is- null.
- Since:
- 2.8.0
 
- 
isFileNewerpublic static boolean isFileNewer(File file, ChronoLocalDateTime<?> chronoLocalDateTime, ZoneId zoneId) Tests if the specifiedFileis newer than the specifiedChronoLocalDateTimeat the specifiedZoneId.- Parameters:
- file- the- Fileof 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:
- UncheckedIOException- if an I/O error occurs
- NullPointerException- if the file, local date time or zone ID is- null.
- Since:
- 2.8.0
 
- 
isFileNewerTests if the specifiedFileis newer than the specifiedChronoZonedDateTime.- Parameters:
- file- the- Fileof which the modification date must be compared.
- chronoZonedDateTime- the date reference.
- Returns:
- true if the Fileexists and has been modified after the givenChronoZonedDateTime.
- Throws:
- NullPointerException- if the file or zoned date time is- null.
- UncheckedIOException- if an I/O error occurs
- Since:
- 2.8.0
 
- 
isFileNewer- Parameters:
- file- the- Fileof which the modification date must be compared.
- date- the date reference.
- Returns:
- true if the Fileexists and has been modified after the givenDate.
- Throws:
- UncheckedIOException- if an I/O error occurs
- NullPointerException- if the file or date is- null.
 
- 
isFileNewer- Parameters:
- file- the- Fileof which the modification date must be compared.
- reference- the- Fileof which the modification date is used.
- Returns:
- true if the Fileexists and has been modified more recently than the referenceFile.
- Throws:
- NullPointerException- if the file or reference file is- null.
- UncheckedIOException- if the reference file doesn't exist.
 
- 
isFileNewer- Parameters:
- file- the- Fileof which the modification date must be compared.
- fileTime- the file time reference.
- Returns:
- true if the Fileexists and has been modified after the givenFileTime.
- Throws:
- IOException- if an I/O error occurs.
- NullPointerException- if the file or local date is- null.
- Since:
- 2.12.0
 
- 
isFileNewer- Parameters:
- file- the- Fileof which the modification date must be compared.
- instant- the date reference.
- Returns:
- true if the Fileexists and has been modified after the givenInstant.
- Throws:
- NullPointerException- if the file or instant is- null.
- UncheckedIOException- if an I/O error occurs
- Since:
- 2.8.0
 
- 
isFileNewerTests if the specifiedFileis newer than the specified time reference.- Parameters:
- file- the- Fileof 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:
- UncheckedIOException- if an I/O error occurs
- NullPointerException- if the file is- null.
 
- 
isFileNewerTests if the specifiedFileis newer than the specifiedOffsetDateTime.- Parameters:
- file- the- Fileof which the modification date must be compared
- offsetDateTime- the date reference
- Returns:
- true if the Fileexists and has been modified before the givenOffsetDateTime.
- Throws:
- UncheckedIOException- if an I/O error occurs
- NullPointerException- if the file or zoned date time is- null
- Since:
- 2.12.0
 
- 
isFileOlderTests if the specifiedFileis older than the specifiedChronoLocalDateat the end of day.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- the- Fileof 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:
- NullPointerException- if the file or local date is- null.
- UncheckedIOException- if an I/O error occurs
- Since:
- 2.8.0
- See Also:
 
- 
isFileOlderTests 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- the- Fileof 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:
- UncheckedIOException- if an I/O error occurs
- NullPointerException- if the file, local date or local time is- null.
- Since:
- 2.8.0
- See Also:
 
- 
isFileOlderpublic static boolean isFileOlder(File file, ChronoLocalDate chronoLocalDate, OffsetTime offsetTime) Tests if the specifiedFileis older than the specifiedChronoLocalDateat the specifiedOffsetTime.- Parameters:
- file- the- Fileof which the modification date must be compared
- chronoLocalDate- the date reference
- offsetTime- the time reference
- Returns:
- true if the Fileexists and has been modified after the givenChronoLocalDateat the givenOffsetTime.
- Throws:
- NullPointerException- if the file, local date or zone ID is- null
- UncheckedIOException- if an I/O error occurs
- Since:
- 2.12.0
 
- 
isFileOlderTests 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- the- Fileof 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:
- NullPointerException- if the file or local date time is- null.
- UncheckedIOException- if an I/O error occurs
- Since:
- 2.8.0
- See Also:
 
- 
isFileOlderpublic static boolean isFileOlder(File file, ChronoLocalDateTime<?> chronoLocalDateTime, ZoneId zoneId) Tests if the specifiedFileis older than the specifiedChronoLocalDateTimeat the specifiedZoneId.- Parameters:
- file- the- Fileof 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:
- NullPointerException- if the file, local date time or zone ID is- null.
- UncheckedIOException- if an I/O error occurs
- Since:
- 2.8.0
 
- 
isFileOlderTests if the specifiedFileis older than the specifiedChronoZonedDateTime.- Parameters:
- file- the- Fileof which the modification date must be compared.
- chronoZonedDateTime- the date reference.
- Returns:
- true if the Fileexists and has been modified before the givenChronoZonedDateTime.
- Throws:
- NullPointerException- if the file or zoned date time is- null.
- UncheckedIOException- if an I/O error occurs
- Since:
- 2.8.0
 
- 
isFileOlder- Parameters:
- file- the- Fileof which the modification date must be compared.
- date- the date reference.
- Returns:
- true if the Fileexists and has been modified before the givenDate.
- Throws:
- NullPointerException- if the file or date is- null.
- UncheckedIOException- if an I/O error occurs
 
- 
isFileOlder- Parameters:
- file- the- Fileof which the modification date must be compared.
- reference- the- Fileof which the modification date is used.
- Returns:
- true if the Fileexists and has been modified before the referenceFile.
- Throws:
- NullPointerException- if the file or reference file is- null.
- FileNotFoundException- if the reference file doesn't exist.
- UncheckedIOException- if an I/O error occurs
 
- 
isFileOlder- Parameters:
- file- the- Fileof which the modification date must be compared.
- fileTime- the file time reference.
- Returns:
- true if the Fileexists and has been modified before the givenFileTime.
- Throws:
- IOException- if an I/O error occurs.
- NullPointerException- if the file or local date is- null.
- Since:
- 2.12.0
 
- 
isFileOlder- Parameters:
- file- the- Fileof which the modification date must be compared.
- instant- the date reference.
- Returns:
- true if the Fileexists and has been modified before the givenInstant.
- Throws:
- NullPointerException- if the file or instant is- null.
- Since:
- 2.8.0
 
- 
isFileOlderTests if the specifiedFileis older than the specified time reference.- Parameters:
- file- the- Fileof 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:
- NullPointerException- if the file is- null.
- UncheckedIOException- if an I/O error occurs
 
- 
isFileOlderTests if the specifiedFileis older than the specifiedOffsetDateTime.- Parameters:
- file- the- Fileof which the modification date must be compared
- offsetDateTime- the date reference
- Returns:
- true if the Fileexists and has been modified before the givenOffsetDateTime.
- Throws:
- NullPointerException- if the file or zoned date time is- null
- Since:
- 2.12.0
 
- 
isRegularFileTests 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 regular file, or it cannot be determined if the file is a regular file or not.
- Throws:
- SecurityException- In the case of the default provider, and a security manager is installed, the- checkReadmethod is invoked to check read access to the directory.
- Since:
- 2.9.0
 
- 
isSymlinkTests 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, may be null.
- Returns:
- true if the file is a symbolic link, see Files.isSymbolicLink(Path path).
- Since:
- 2.0
- See Also:
 
- 
iterateFilespublic static Iterator<File> iterateFiles(File directory, IOFileFilter fileFilter, IOFileFilter dirFilter) Iterates over the files in given directory (and optionally its subdirectories).The resulting iterator MUST be consumed in its entirety in order to close its underlying stream. All files found are filtered by an IOFileFilter. - Parameters:
- directory- the directory to search in
- fileFilter- filter to apply when finding files.
- dirFilter- optional filter to apply when finding subdirectories. If this parameter is- null, subdirectories will not be included in the search. Use TrueFileFilter.INSTANCE to match all directories.
- Returns:
- an iterator of Filefor the matching files
- Since:
- 1.2
- See Also:
 
- 
iterateFilesIterates 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 in
- extensions- an array of extensions, for example, {"java","xml"}. If this parameter is- null, all files are returned.
- recursive- if true all subdirectories are searched as well
- Returns:
- an iterator of Filewith the matching files
- Since:
- 1.2
 
- 
iterateFilesAndDirspublic static Iterator<File> iterateFilesAndDirs(File directory, IOFileFilter fileFilter, IOFileFilter dirFilter) Iterates over the files in given directory (and optionally its subdirectories).The resulting iterator MUST be consumed in its entirety in order to close its underlying stream. All files found are filtered by an IOFileFilter. The resulting iterator includes the subdirectories themselves. - Parameters:
- directory- the directory to search in
- fileFilter- filter to apply when finding files.
- dirFilter- optional filter to apply when finding subdirectories. If this parameter is- null, subdirectories will not be included in the search. Use TrueFileFilter.INSTANCE to match all directories.
- Returns:
- an iterator of Filefor the matching files
- Since:
- 2.2
- See Also:
 
- 
lastModifiedReturns the last modification time in milliseconds viaFiles.getLastModifiedTime(Path, LinkOption...).For the best precision, use lastModifiedFileTime(File).Use this method to avoid issues with File.lastModified()like JDK-8177809 whereFile.lastModified()is losing milliseconds (always ends in 000). This bug exists in OpenJDK 8 and 9, and is fixed in 10.- Parameters:
- file- The File to query.
- Returns:
- See FileTime.toMillis().
- Throws:
- IOException- if an I/O error occurs.
- Since:
- 2.9.0
 
- 
lastModifiedFileTimeReturns the last modificationFileTimeviaFiles.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 Files.getLastModifiedTime(Path, LinkOption...).
- Throws:
- IOException- if an I/O error occurs.
- Since:
- 2.12.0
 
- 
lastModifiedUncheckedReturns the last modification time in milliseconds viaFiles.getLastModifiedTime(Path, LinkOption...).For the best precision, use lastModifiedFileTime(File).Use this method to avoid issues with File.lastModified()like JDK-8177809 whereFile.lastModified()is losing milliseconds (always ends in 000). This bug exists in OpenJDK 8 and 9, and is fixed in 10.- Parameters:
- file- The File to query.
- Returns:
- See FileTime.toMillis().
- Throws:
- UncheckedIOException- if an I/O error occurs.
- Since:
- 2.9.0
 
- 
lineIteratorReturns an Iterator for the lines in aFileusing the default encoding for the VM.- Parameters:
- file- the file to open for input, must not be- null
- Returns:
- an Iterator of the lines in the file, never null
- Throws:
- NullPointerException- if file is- null.
- FileNotFoundException- if the file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading.
- IOException- if an I/O error occurs.
- Since:
- 1.3
- See Also:
 
- 
lineIteratorReturns 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 using a try-with-resources block or calling theLineIterator.close()method.The recommended usage pattern is: LineIterator it = FileUtils.lineIterator(file, StandardCharsets.UTF_8.name()); 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 be- null
- charsetName- the name of the requested charset,- nullmeans platform default
- Returns:
- a LineIterator for lines in the file, never null; MUST be closed by the caller.
- Throws:
- NullPointerException- if file is- null.
- FileNotFoundException- if the file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading.
- IOException- if an I/O error occurs.
- Since:
- 1.2
 
- 
listFilespublic static Collection<File> listFiles(File directory, IOFileFilter fileFilter, IOFileFilter dirFilter) Finds files within a given directory (and optionally its subdirectories). All files found are filtered by an IOFileFilter.If your search should recurse into subdirectories you can pass in an IOFileFilter for directories. You don't need to bind a DirectoryFileFilter (via logical AND) to this filter. This method does that for you. An example: If you want to search through all directories called "temp" you pass in FileFilterUtils.NameFileFilter("temp")Another common usage of this method is find files in a directory tree but ignoring the directories generated CVS. You can simply pass in FileFilterUtils.makeCVSAware(null).- Parameters:
- directory- the directory to search in
- fileFilter- filter to apply when finding files. Must not be- null, use- TrueFileFilter.INSTANCEto match all files in selected directories.
- dirFilter- optional filter to apply when finding subdirectories. If this parameter is- null, subdirectories will not be included in the search. Use- TrueFileFilter.INSTANCEto match all directories.
- Returns:
- a collection of Filewith the matching files
- See Also:
 
- 
listFilesLists files within a given directory (and optionally its subdirectories) which match an array of extensions.- Parameters:
- directory- the directory to search in
- extensions- an array of extensions, for example, {"java","xml"}. If this parameter is- null, all files are returned.
- recursive- if true all subdirectories are searched as well
- Returns:
- a collection of Filewith the matching files
 
- 
listFilesAndDirspublic static Collection<File> listFilesAndDirs(File directory, IOFileFilter fileFilter, IOFileFilter dirFilter) Finds files within a given directory (and optionally its subdirectories). All files found are filtered by an IOFileFilter.The resulting collection includes the starting directory and any subdirectories that match the directory filter. - Parameters:
- directory- the directory to search in
- fileFilter- filter to apply when finding files.
- dirFilter- optional filter to apply when finding subdirectories. If this parameter is- null, subdirectories will not be included in the search. Use TrueFileFilter.INSTANCE to match all directories.
- Returns:
- a collection of Filewith the matching files
- Since:
- 2.2
- See Also:
 
- 
moveDirectoryMoves a directory.When the destination directory is on another file system, do a "copy and delete". - Parameters:
- srcDir- the directory to be moved.
- destDir- the destination directory.
- Throws:
- NullPointerException- if any of the given- Files are- null.
- IllegalArgumentException- if- srcDirexists but is not a directory
- FileNotFoundException- if the source does not exist.
- IOException- if an error occurs or setting the last-modified time didn't succeed.
- Since:
- 1.4
 
- 
moveDirectoryToDirectorypublic static void moveDirectoryToDirectory(File source, File destDir, boolean createDestDir) throws IOException Moves a directory to another directory.If createDestDiris true, creates all destination parent directories, including any necessary but non-existent parent directories.- Parameters:
- source- the directory to be moved.
- destDir- the destination file.
- createDestDir- If- truecreate the destination directory, otherwise if- falsethrow an IOException.
- Throws:
- NullPointerException- if any of the given- Files are- null.
- IllegalArgumentException- if the source or destination is invalid.
- FileNotFoundException- if the source does not exist.
- IOException- if the directory was not created along with all its parent directories, if enabled.
- IOException- if an error occurs or setting the last-modified time didn't succeed.
- SecurityException- See- File.mkdirs().
- Since:
- 1.4
 
- 
moveFileMoves a file preserving attributes.Shorthand for moveFile(srcFile, destFile, StandardCopyOption.COPY_ATTRIBUTES).When the destination file is on another file system, do a "copy and delete". - Parameters:
- srcFile- the file to be moved.
- destFile- the destination file.
- Throws:
- NullPointerException- if any of the given- Files are- null.
- FileExistsException- if the destination file exists.
- FileNotFoundException- if the source file does not exist.
- IllegalArgumentException- if- srcFileis a directory
- IOException- if an error occurs.
- Since:
- 1.4
 
- 
moveFilepublic static void moveFile(File srcFile, File destFile, CopyOption... copyOptions) throws IOException Moves a file.When the destination file is on another file system, do a "copy and delete". - Parameters:
- srcFile- the file to be moved.
- destFile- the destination file.
- copyOptions- Copy options.
- Throws:
- NullPointerException- if any of the given- Files are- null.
- FileExistsException- if the destination file exists.
- FileNotFoundException- if the source file does not exist.
- IllegalArgumentException- if- srcFileis a directory
- IOException- if an error occurs or setting the last-modified time didn't succeed.
- Since:
- 2.9.0
 
- 
moveFileToDirectorypublic static void moveFileToDirectory(File srcFile, File destDir, boolean createDestDir) throws IOException Moves a file into a directory.If createDestDiris true, creates all destination parent directories, including any necessary but non-existent parent directories.- Parameters:
- srcFile- the file to be moved.
- destDir- the directory to move the file into
- createDestDir- if- truecreate the destination directory. If- falsethrow an IOException if the destination directory does not already exist.
- Throws:
- NullPointerException- if any of the given- Files are- null.
- FileExistsException- if the destination file exists.
- FileNotFoundException- if the source file does not exist.
- IOException- if source or destination is invalid.
- IOException- if the directory was not created along with all its parent directories, if enabled.
- IOException- if an error occurs or setting the last-modified time didn't succeed.
- SecurityException- See- File.mkdirs().
- IllegalArgumentException- if- destDirexists but is not a directory
- Since:
- 1.4
 
- 
moveToDirectorypublic static void moveToDirectory(File src, File destDir, boolean createDestDir) throws IOException Moves a file or directory into a destination directory.If createDestDiris true, creates all destination parent directories, including any necessary but non-existent parent directories.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- if- truecreate the destination directory. If- falsethrow an IOException if the destination directory does not already exist.
- Throws:
- NullPointerException- if any of the given- Files are- null.
- FileExistsException- if the directory or file exists in the destination directory.
- FileNotFoundException- if the source file does not exist.
- IOException- if source or destination is invalid.
- IOException- if an error occurs or setting the last-modified time didn't succeed.
- Since:
- 1.4
 
- 
newOutputStreamCreates a new OutputStream by opening or creating a file, returning an output stream that may be used to write bytes to the file.- Parameters:
- file- the File.
- append- Whether or not to append.
- Returns:
- a new OutputStream.
- Throws:
- IOException- if an I/O error occurs.
- Since:
- 2.12.0
- See Also:
 
- 
openInputStreamOpens 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 be- null
- Returns:
- a new FileInputStreamfor the specified file
- Throws:
- NullPointerException- if file is- null.
- FileNotFoundException- if the file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading.
- IOException- See FileNotFoundException above, FileNotFoundException is a subclass of IOException.
- Since:
- 1.3
 
- 
openOutputStreamOpens 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 be- null
- Returns:
- a new FileOutputStreamfor the specified file
- Throws:
- NullPointerException- if the file object is- null.
- IllegalArgumentException- if the file object is a directory
- IllegalArgumentException- if the file is not writable.
- IOException- if the directories could not be created.
- Since:
- 1.3
 
- 
openOutputStreamOpens 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 be- null
- append- if- true, then bytes will be added to the end of the file rather than overwriting
- Returns:
- a new FileOutputStreamfor the specified file
- Throws:
- NullPointerException- if the file object is- null.
- IllegalArgumentException- if the file object is a directory
- IOException- if the directories could not be created, or the file is not writable
- Since:
- 2.1
 
- 
readFileToByteArrayReads the contents of a file into a byte array. The file is always closed.- Parameters:
- file- the file to read, must not be- null
- Returns:
- the file contents, never null
- Throws:
- NullPointerException- if file is- null.
- IOException- if an I/O error occurs, including when the file does not exist, is a directory rather than a regular file, or for some other reason why the file cannot be opened for reading.
- Since:
- 1.1
 
- 
readFileToStringDeprecated.UsereadFileToString(File, Charset)instead (and specify the appropriate encoding)Reads the contents of a file into a String using the virtual machine'sdefault charset. The file is always closed.- Parameters:
- file- the file to read, must not be- null
- Returns:
- the file contents, never null
- Throws:
- NullPointerException- if file is- null.
- IOException- if an I/O error occurs, including when the file does not exist, is a directory rather than a regular file, or for some other reason why the file cannot be opened for reading.
- Since:
- 1.3.1
 
- 
readFileToStringReads the contents of a file into a String. The file is always closed.- Parameters:
- file- the file to read, must not be- null
- charsetName- the name of the requested charset,- nullmeans platform default
- Returns:
- the file contents, never null
- Throws:
- NullPointerException- if file is- null.
- IOException- if an I/O error occurs, including when the file does not exist, is a directory rather than a regular file, or for some other reason why the file cannot be opened for reading.
- Since:
- 2.3
 
- 
readFileToStringReads the contents of a file into a String. The file is always closed.- Parameters:
- file- the file to read, must not be- null
- charsetName- the name of the requested charset,- nullmeans platform default
- Returns:
- the file contents, never null
- Throws:
- NullPointerException- if file is- null.
- IOException- if an I/O error occurs, including when the file does not exist, is a directory rather than a regular file, or for some other reason why the file cannot be opened for reading.
- UnsupportedCharsetException- if the named charset is unavailable.
- Since:
- 2.3
 
- 
readLinesDeprecated.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 virtual machine'sdefault charset. The file is always closed.- Parameters:
- file- the file to read, must not be- null
- Returns:
- the list of Strings representing each line in the file, never null
- Throws:
- NullPointerException- if file is- null.
- IOException- if an I/O error occurs, including when the file does not exist, is a directory rather than a regular file, or for some other reason why the file cannot be opened for reading.
- Since:
- 1.3
 
- 
readLinesReads 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 be- null
- charset- the charset to use,- nullmeans platform default
- Returns:
- the list of Strings representing each line in the file, never null
- Throws:
- NullPointerException- if file is- null.
- IOException- if an I/O error occurs, including when the file does not exist, is a directory rather than a regular file, or for some other reason why the file cannot be opened for reading.
- Since:
- 2.3
 
- 
readLinesReads 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 be- null
- charsetName- the name of the requested charset,- nullmeans platform default
- Returns:
- the list of Strings representing each line in the file, never null
- Throws:
- NullPointerException- if file is- null.
- IOException- if an I/O error occurs, including when the file does not exist, is a directory rather than a regular file, or for some other reason why the file cannot be opened for reading.
- UnsupportedCharsetException- if the named charset is unavailable.
- Since:
- 1.1
 
- 
sizeOfReturns 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 be- null).
- Returns:
- the length of the file, or recursive size of the directory, provided (in bytes).
- Throws:
- NullPointerException- if the file is- null.
- IllegalArgumentException- if the file does not exist.
- UncheckedIOException- if an IO error occurs.
- Since:
- 2.0
 
- 
sizeOfAsBigIntegerReturns 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 be- null).
- Returns:
- the length of the file, or recursive size of the directory, provided (in bytes).
- Throws:
- NullPointerException- if the file is- null.
- IllegalArgumentException- if the file does not exist.
- UncheckedIOException- if an IO error occurs.
- Since:
- 2.4
 
- 
sizeOfDirectoryCounts 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 be- null.
- 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:
- IllegalArgumentException- if the given- Fileexists but is not a directory
- NullPointerException- if the directory is- null.
- UncheckedIOException- if an IO error occurs.
 
- 
sizeOfDirectoryAsBigIntegerCounts the size of a directory recursively (sum of the length of all files).- Parameters:
- directory- directory to inspect, must not be- null.
- Returns:
- size of directory in bytes, 0 if directory is security restricted.
- Throws:
- IllegalArgumentException- if the given- Fileexists but is not a directory
- NullPointerException- if the directory is- null.
- UncheckedIOException- if an IO error occurs.
- Since:
- 2.4
 
- 
streamFilespublic static Stream<File> streamFiles(File directory, boolean recursive, String... extensions) throws IOException Streams over the files in a given directory (and optionally its subdirectories) which match an array of extensions.The returned Streammay wrap one or moreDirectoryStreams. When you require timely disposal of file system resources, use atry-with-resources block to ensure invocation of the stream'sBaseStream.close()method after the stream operations are completed. Calling a closed stream causes aIllegalStateException.- Parameters:
- directory- the directory to search in
- recursive- if true all subdirectories are searched as well
- extensions- an array of extensions, for example, {"java","xml"}. If this parameter is- null, all files are returned.
- Returns:
- a Stream of Filefor matching files.
- Throws:
- IOException- if an I/O error is thrown when accessing the starting file.
- Since:
- 2.9.0
 
- 
toFileConverts from aURLto aFile.Syntax such as file:///my%20docs/file.txtwill be correctly decoded to/my docs/file.txt. UTF-8 is used 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,- nullreturns- null
- Returns:
- the equivalent Fileobject, ornullif the URL's protocol is notfile
 
- 
toFilesConverts each of an array ofURLto aFile.Returns an array of the same size as the input. If the input is null, an empty array is returned. If the input containsnull, the output array containsnullat the same index.This method will decode the URL. Syntax such as file:///my%20docs/file.txtwill be correctly decoded to/my docs/file.txt.- Parameters:
- urls- the file URLs to convert,- nullreturns empty array
- Returns:
- a non-nullarray of Files matching the input, with anullitem if there was anullat that index in the input array
- Throws:
- IllegalArgumentException- if any file is not a URL file
- IllegalArgumentException- if any file is incorrectly encoded
- Since:
- 1.1
 
- 
touchImplements behavior similar to the Unix "touch" utility. Creates a new file with size 0, or, if the file exists, just updates the file's modified time. This method throws an IOException if the last modified date of the file cannot be set. It creates parent directories if they do not exist.- Parameters:
- file- the File to touch.
- Throws:
- NullPointerException- if the parameter is- null.
- IOException- if setting the last-modified time failed or an I/O problem occurs.
 
- 
toURLs- Parameters:
- files- the files to convert, must not be- null
- Returns:
- an array of URLs matching the input
- Throws:
- IOException- if a file cannot be converted
- NullPointerException- if any argument is null
 
- 
waitForWaits for the file system to detect a file's presence, with a timeout.This method repeatedly tests Files.exists(Path, LinkOption...)until it returns true up to the maximum time specified in seconds.- Parameters:
- file- the file to check, must not be- null
- seconds- the maximum time in seconds to wait
- Returns:
- true if file exists
- Throws:
- NullPointerException- if the file is- null
 
- 
writeDeprecated.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 virtual machine'sdefault charset.- Parameters:
- file- the file to write
- data- the content to write to the file
- Throws:
- IOException- in case of an I/O error
- Since:
- 2.0
 
- 
write@Deprecated public static void write(File file, CharSequence data, boolean append) throws IOException Deprecated.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 virtual machine'sdefault charset.- Parameters:
- file- the file to write
- data- the content to write to the file
- append- if- true, then the data will be added to the end of the file rather than overwriting
- Throws:
- IOException- in case of an I/O error
- Since:
- 2.1
 
- 
writeWrites a CharSequence to a file creating the file if it does not exist.- Parameters:
- file- the file to write
- data- the content to write to the file
- charset- the name of the requested charset,- nullmeans platform default
- Throws:
- IOException- in case of an I/O error
- Since:
- 2.3
 
- 
writepublic static void write(File file, CharSequence data, Charset charset, boolean append) throws IOException Writes a CharSequence to a file creating the file if it does not exist.- Parameters:
- file- the file to write
- data- the content to write to the file
- charset- the charset to use,- nullmeans platform default
- append- if- true, then the data will be added to the end of the file rather than overwriting
- Throws:
- IOException- in case of an I/O error
- Since:
- 2.3
 
- 
writeWrites a CharSequence to a file creating the file if it does not exist.- Parameters:
- file- the file to write
- data- the content to write to the file
- charsetName- the name of the requested charset,- nullmeans platform default
- Throws:
- IOException- in case of an I/O error
- UnsupportedEncodingException- if the encoding is not supported by the VM
- Since:
- 2.0
 
- 
writepublic static void write(File file, CharSequence data, String charsetName, boolean append) throws IOException Writes a CharSequence to a file creating the file if it does not exist.- Parameters:
- file- the file to write
- data- the content to write to the file
- charsetName- the name of the requested charset,- nullmeans platform default
- append- if- true, then the data will be added to the end of the file rather than overwriting
- Throws:
- IOException- in case of an I/O error
- UnsupportedCharsetException- if the encoding is not supported by the VM
- Since:
- 2.1
 
- 
writeByteArrayToFileWrites a byte array to a file creating the file if it does not exist. The parent directories of the file will be created if they do not exist.- Parameters:
- file- the file to write to
- data- the content to write to the file
- Throws:
- IOException- in case of an I/O error
- Since:
- 1.1
 
- 
writeByteArrayToFileWrites a byte array to a file creating the file if it does not exist.- Parameters:
- file- the file to write to
- data- the content to write to the file
- append- if- true, then bytes will be added to the end of the file rather than overwriting
- Throws:
- IOException- in case of an I/O error
- Since:
- 2.1
 
- 
writeByteArrayToFilepublic static void writeByteArrayToFile(File file, byte[] data, int off, int len) throws IOException Writeslenbytes from the specified byte array starting at offsetoffto a file, creating the file if it does not exist.- Parameters:
- file- the file to write to
- data- the content to write to the file
- off- the start offset in the data
- len- the number of bytes to write
- Throws:
- IOException- in case of an I/O error
- Since:
- 2.5
 
- 
writeByteArrayToFilepublic static void writeByteArrayToFile(File file, byte[] data, int off, int len, boolean append) throws IOException Writeslenbytes from the specified byte array starting at offsetoffto a file, creating the file if it does not exist.- Parameters:
- file- the file to write to
- data- the content to write to the file
- off- the start offset in the data
- len- the number of bytes to write
- append- if- true, then bytes will be added to the end of the file rather than overwriting
- Throws:
- IOException- in case of an I/O error
- Since:
- 2.5
 
- 
writeLinesWrites 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 to
- lines- the lines to write,- nullentries produce blank lines
- Throws:
- IOException- in case of an I/O error
- Since:
- 1.3
 
- 
writeLinesWrites 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 to
- lines- the lines to write,- nullentries produce blank lines
- append- if- true, then the lines will be added to the end of the file rather than overwriting
- Throws:
- IOException- in case of an I/O error
- Since:
- 2.1
 
- 
writeLinesWrites 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 to
- lines- the lines to write,- nullentries produce blank lines
- lineEnding- the line separator to use,- nullis system default
- Throws:
- IOException- in case of an I/O error
- Since:
- 1.3
 
- 
writeLinespublic static void writeLines(File file, Collection<?> lines, String lineEnding, boolean append) throws IOException Writes thetoString()value of each item in a collection to the specifiedFileline by line. The default VM encoding and the specified line ending will be used.- Parameters:
- file- the file to write to
- lines- the lines to write,- nullentries produce blank lines
- lineEnding- the line separator to use,- nullis system default
- append- if- true, then the lines will be added to the end of the file rather than overwriting
- Throws:
- IOException- in case of an I/O error
- Since:
- 2.1
 
- 
writeLinespublic static void writeLines(File file, String charsetName, Collection<?> lines) throws IOException Writes thetoString()value of each item in a collection to the specifiedFileline by line. The specified character encoding and the default line ending will be used. The parent directories of the file will be created if they do not exist.- Parameters:
- file- the file to write to
- charsetName- the name of the requested charset,- nullmeans platform default
- lines- the lines to write,- nullentries produce blank lines
- Throws:
- IOException- in case of an I/O error
- UnsupportedEncodingException- if the encoding is not supported by the VM
- Since:
- 1.1
 
- 
writeLinespublic static void writeLines(File file, String charsetName, Collection<?> lines, boolean append) throws IOException Writes thetoString()value of each item in a collection to the specifiedFileline by line, optionally appending. The specified character encoding and the default line ending will be used.- Parameters:
- file- the file to write to
- charsetName- the name of the requested charset,- nullmeans platform default
- lines- the lines to write,- nullentries produce blank lines
- append- if- true, then the lines will be added to the end of the file rather than overwriting
- Throws:
- IOException- in case of an I/O error
- UnsupportedEncodingException- if the encoding is not supported by the VM
- Since:
- 2.1
 
- 
writeLinespublic static void writeLines(File file, String charsetName, Collection<?> lines, String lineEnding) throws IOException Writes thetoString()value of each item in a collection to the specifiedFileline by line. The specified character encoding and the line ending will be used. The parent directories of the file will be created if they do not exist.- Parameters:
- file- the file to write to
- charsetName- the name of the requested charset,- nullmeans platform default
- lines- the lines to write,- nullentries produce blank lines
- lineEnding- the line separator to use,- nullis system default
- Throws:
- IOException- in case of an I/O error
- UnsupportedEncodingException- if the encoding is not supported by the VM
- Since:
- 1.1
 
- 
writeLinespublic static void writeLines(File file, String charsetName, Collection<?> lines, String lineEnding, boolean append) throws IOException Writes thetoString()value of each item in a collection to the specifiedFileline by line. The specified character encoding and the line ending will be used.- Parameters:
- file- the file to write to
- charsetName- the name of the requested charset,- nullmeans platform default
- lines- the lines to write,- nullentries produce blank lines
- lineEnding- the line separator to use,- nullis system default
- append- if- true, then the lines will be added to the end of the file rather than overwriting
- Throws:
- IOException- in case of an I/O error
- UnsupportedEncodingException- if the encoding is not supported by the VM
- Since:
- 2.1
 
- 
writeStringToFileDeprecated.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 virtual machine'sdefault charset.- Parameters:
- file- the file to write
- data- the content to write to the file
- Throws:
- IOException- in case of an I/O error
 
- 
writeStringToFile@Deprecated public static void writeStringToFile(File file, String data, boolean append) throws IOException Deprecated.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 virtual machine'sdefault charset.- Parameters:
- file- the file to write
- data- the content to write to the file
- append- if- true, then the String will be added to the end of the file rather than overwriting
- Throws:
- IOException- in case of an I/O error
- Since:
- 2.1
 
- 
writeStringToFileWrites a String to a file creating the file if it does not exist. The parent directories of the file will be created if they do not exist.- Parameters:
- file- the file to write
- data- the content to write to the file
- charset- the charset to use,- nullmeans platform default
- Throws:
- IOException- in case of an I/O error
- UnsupportedEncodingException- if the encoding is not supported by the VM
- Since:
- 2.4
 
- 
writeStringToFilepublic static void writeStringToFile(File file, String data, Charset charset, boolean append) throws IOException Writes a String to a file, creating the file if it does not exist. The parent directories of the file are created if they do not exist.- Parameters:
- file- the file to write
- data- the content to write to the file
- charset- the charset to use,- nullmeans platform default
- append- if- true, then the String will be added to the end of the file rather than overwriting
- Throws:
- IOException- in case of an I/O error
- Since:
- 2.3
 
- 
writeStringToFileWrites a String to a file, creating the file if it does not exist. The parent directories of the file are created if they do not exist.- Parameters:
- file- the file to write
- data- the content to write to the file
- charsetName- the name of the requested charset,- nullmeans platform default
- Throws:
- IOException- in case of an I/O error
- UnsupportedEncodingException- if the encoding is not supported by the VM
 
- 
writeStringToFilepublic static void writeStringToFile(File file, String data, String charsetName, boolean append) throws IOException Writes a String to a file, creating the file if it does not exist. The parent directories of the file are created if they do not exist.- Parameters:
- file- the file to write
- data- the content to write to the file
- charsetName- the name of the requested charset,- nullmeans platform default
- append- if- true, then the String will be added to the end of the file rather than overwriting
- Throws:
- IOException- in case of an I/O error
- UnsupportedCharsetException- if the encoding is not supported by the VM
- Since:
- 2.1
 
 
-