Methods Summary |
---|
public static java.lang.String | byteCountToDisplaySize(long size)Returns a human-readable version of the file size, where the input
represents a specific number of bytes.
String displaySize;
if (size / ONE_GB > 0) {
displaySize = String.valueOf(size / ONE_GB) + " GB";
} else if (size / ONE_MB > 0) {
displaySize = String.valueOf(size / ONE_MB) + " MB";
} else if (size / ONE_KB > 0) {
displaySize = String.valueOf(size / ONE_KB) + " KB";
} else {
displaySize = String.valueOf(size) + " bytes";
}
return displaySize;
|
public static java.util.zip.Checksum | checksum(java.io.File file, java.util.zip.Checksum checksum)Computes the checksum of a file using the specified checksum object.
Multiple files may be checked using one Checksum instance
if desired simply by reusing the same checksum object.
For example:
long csum = FileUtils.checksum(file, new CRC32()).getValue();
if (file.isDirectory()) {
throw new IllegalArgumentException("Checksums can't be computed on directories");
}
InputStream in = null;
try {
in = new CheckedInputStream(new FileInputStream(file), checksum);
IOUtils.copy(in, new NullOutputStream());
} finally {
IOUtils.closeQuietly(in);
}
return checksum;
|
public static long | checksumCRC32(java.io.File file)Computes the checksum of a file using the CRC32 checksum routine.
The value of the checksum is returned.
CRC32 crc = new CRC32();
checksum(file, crc);
return crc.getValue();
|
public static void | cleanDirectory(java.io.File directory)Cleans a directory without deleting it.
if (!directory.exists()) {
String message = directory + " does not exist";
throw new IllegalArgumentException(message);
}
if (!directory.isDirectory()) {
String message = directory + " is not a directory";
throw new IllegalArgumentException(message);
}
File[] files = directory.listFiles();
if (files == null) { // null if security restricted
throw new IOException("Failed to list contents of " + directory);
}
IOException exception = null;
for (int i = 0; i < files.length; i++) {
File file = files[i];
try {
forceDelete(file);
} catch (IOException ioe) {
exception = ioe;
}
}
if (null != exception) {
throw exception;
}
|
private static void | cleanDirectoryOnExit(java.io.File directory)Cleans a directory without deleting it.
if (!directory.exists()) {
String message = directory + " does not exist";
throw new IllegalArgumentException(message);
}
if (!directory.isDirectory()) {
String message = directory + " is not a directory";
throw new IllegalArgumentException(message);
}
File[] files = directory.listFiles();
if (files == null) { // null if security restricted
throw new IOException("Failed to list contents of " + directory);
}
IOException exception = null;
for (int i = 0; i < files.length; i++) {
File file = files[i];
try {
forceDeleteOnExit(file);
} catch (IOException ioe) {
exception = ioe;
}
}
if (null != exception) {
throw exception;
}
|
public static boolean | contentEquals(java.io.File file1, java.io.File file2)Compares the contents of two files to determine if they are equal or not.
This method checks to see if the two files are different lengths
or if they point to the same file, before resorting to byte-by-byte
comparison of the contents.
Code origin: Avalon
boolean file1Exists = file1.exists();
if (file1Exists != file2.exists()) {
return false;
}
if (!file1Exists) {
// two not existing files are equal
return true;
}
if (file1.isDirectory() || file2.isDirectory()) {
// don't want to compare directory contents
throw new IOException("Can't compare directories, only files");
}
if (file1.length() != file2.length()) {
// lengths differ, cannot be equal
return false;
}
if (file1.getCanonicalFile().equals(file2.getCanonicalFile())) {
// same file
return true;
}
InputStream input1 = null;
InputStream input2 = null;
try {
input1 = new FileInputStream(file1);
input2 = new FileInputStream(file2);
return IOUtils.contentEquals(input1, input2);
} finally {
IOUtils.closeQuietly(input1);
IOUtils.closeQuietly(input2);
}
|
public static java.io.File[] | convertFileCollectionToFileArray(java.util.Collection files)Converts a Collection containing java.io.File instanced into array
representation. This is to account for the difference between
File.listFiles() and FileUtils.listFiles().
return (File[]) files.toArray(new File[files.size()]);
|
public static void | copyDirectory(java.io.File srcDir, java.io.File destDir)Copies a whole directory to a new location preserving the file dates.
This method copies the specified directory and all its child
directories and files to the specified destination.
The destination is the new location and name of the directory.
The destination directory is created if it does not exist.
If the destination directory did exist, then this method merges
the source with the destination, with the source taking precedence.
copyDirectory(srcDir, destDir, true);
|
public static void | copyDirectory(java.io.File srcDir, java.io.File destDir, boolean preserveFileDate)Copies a whole directory to a new location.
This method copies the contents of the specified source directory
to within the specified destination directory.
The destination directory is created if it does not exist.
If the destination directory did exist, then this method merges
the source with the destination, with the source taking precedence.
copyDirectory(srcDir, destDir, null, preserveFileDate);
|
public static void | copyDirectory(java.io.File srcDir, java.io.File destDir, java.io.FileFilter filter)Copies a filtered directory to a new location preserving the file dates.
This method copies the contents of the specified source directory
to within the specified destination directory.
The destination directory is created if it does not exist.
If the destination directory did exist, then this method merges
the source with the destination, with the source taking precedence.
Example: Copy directories only
// only copy the directory structure
FileUtils.copyDirectory(srcDir, destDir, DirectoryFileFilter.DIRECTORY);
Example: Copy directories and txt files
// Create a filter for ".txt" files
IOFileFilter txtSuffixFilter = FileFilterUtils.suffixFileFilter(".txt");
IOFileFilter txtFiles = FileFilterUtils.andFileFilter(FileFileFilter.FILE, txtSuffixFilter);
// Create a filter for either directories or ".txt" files
FileFilter filter = FileFilterUtils.orFileFilter(DirectoryFileFilter.DIRECTORY, txtFiles);
// Copy using the filter
FileUtils.copyDirectory(srcDir, destDir, filter);
copyDirectory(srcDir, destDir, filter, true);
|
public static void | copyDirectory(java.io.File srcDir, java.io.File destDir, java.io.FileFilter filter, boolean preserveFileDate)Copies a filtered directory to a new location.
This method copies the contents of the specified source directory
to within the specified destination directory.
The destination directory is created if it does not exist.
If the destination directory did exist, then this method merges
the source with the destination, with the source taking precedence.
Example: Copy directories only
// only copy the directory structure
FileUtils.copyDirectory(srcDir, destDir, DirectoryFileFilter.DIRECTORY, false);
Example: Copy directories and txt files
// Create a filter for ".txt" files
IOFileFilter txtSuffixFilter = FileFilterUtils.suffixFileFilter(".txt");
IOFileFilter txtFiles = FileFilterUtils.andFileFilter(FileFileFilter.FILE, txtSuffixFilter);
// Create a filter for either directories or ".txt" files
FileFilter filter = FileFilterUtils.orFileFilter(DirectoryFileFilter.DIRECTORY, txtFiles);
// Copy using the filter
FileUtils.copyDirectory(srcDir, destDir, filter, false);
if (srcDir == null) {
throw new NullPointerException("Source must not be null");
}
if (destDir == null) {
throw new NullPointerException("Destination must not be null");
}
if (srcDir.exists() == false) {
throw new FileNotFoundException("Source '" + srcDir + "' does not exist");
}
if (srcDir.isDirectory() == false) {
throw new IOException("Source '" + srcDir + "' exists but is not a directory");
}
if (srcDir.getCanonicalPath().equals(destDir.getCanonicalPath())) {
throw new IOException("Source '" + srcDir + "' and destination '" + destDir + "' are the same");
}
// Cater for destination being directory within the source directory (see IO-141)
List exclusionList = null;
if (destDir.getCanonicalPath().startsWith(srcDir.getCanonicalPath())) {
File[] srcFiles = filter == null ? srcDir.listFiles() : srcDir.listFiles(filter);
if (srcFiles != null && srcFiles.length > 0) {
exclusionList = new ArrayList(srcFiles.length);
for (int i = 0; i < srcFiles.length; i++) {
File copiedFile = new File(destDir, srcFiles[i].getName());
exclusionList.add(copiedFile.getCanonicalPath());
}
}
}
doCopyDirectory(srcDir, destDir, filter, preserveFileDate, exclusionList);
|
public static void | copyDirectoryToDirectory(java.io.File srcDir, java.io.File destDir)Copies a directory to within another directory preserving the file dates.
This method copies the source directory and all its contents to a
directory of the same name in the specified destination directory.
The destination directory is created if it does not exist.
If the destination directory did exist, then this method merges
the source with the destination, with the source taking precedence.
if (srcDir == null) {
throw new NullPointerException("Source must not be null");
}
if (srcDir.exists() && srcDir.isDirectory() == false) {
throw new IllegalArgumentException("Source '" + destDir + "' is not a directory");
}
if (destDir == null) {
throw new NullPointerException("Destination must not be null");
}
if (destDir.exists() && destDir.isDirectory() == false) {
throw new IllegalArgumentException("Destination '" + destDir + "' is not a directory");
}
copyDirectory(srcDir, new File(destDir, srcDir.getName()), true);
|
public static void | copyFile(java.io.File srcFile, java.io.File destFile)Copies a file to a new location preserving the file date.
This method copies the contents of the specified source file to the
specified destination file. The directory holding the destination file is
created if it does not exist. If the destination file exists, then this
method will overwrite it.
copyFile(srcFile, destFile, true);
|
public static void | copyFile(java.io.File srcFile, java.io.File destFile, boolean preserveFileDate)Copies a file to a new location.
This method copies the contents of the specified source file
to the specified destination file.
The directory holding the destination file is created if it does not exist.
If the destination file exists, then this method will overwrite it.
if (srcFile == null) {
throw new NullPointerException("Source must not be null");
}
if (destFile == null) {
throw new NullPointerException("Destination must not be null");
}
if (srcFile.exists() == false) {
throw new FileNotFoundException("Source '" + srcFile + "' does not exist");
}
if (srcFile.isDirectory()) {
throw new IOException("Source '" + srcFile + "' exists but is a directory");
}
if (srcFile.getCanonicalPath().equals(destFile.getCanonicalPath())) {
throw new IOException("Source '" + srcFile + "' and destination '" + destFile + "' are the same");
}
if (destFile.getParentFile() != null && destFile.getParentFile().exists() == false) {
if (destFile.getParentFile().mkdirs() == false) {
throw new IOException("Destination '" + destFile + "' directory cannot be created");
}
}
if (destFile.exists() && destFile.canWrite() == false) {
throw new IOException("Destination '" + destFile + "' exists but is read-only");
}
doCopyFile(srcFile, destFile, preserveFileDate);
|
public static void | copyFileToDirectory(java.io.File srcFile, java.io.File destDir)Copies a file to a directory preserving the file date.
This method copies the contents of the specified source file
to a file of the same name in the specified destination directory.
The destination directory is created if it does not exist.
If the destination file exists, then this method will overwrite it.
copyFileToDirectory(srcFile, destDir, true);
|
public static void | copyFileToDirectory(java.io.File srcFile, java.io.File destDir, boolean preserveFileDate)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.
if (destDir == null) {
throw new NullPointerException("Destination must not be null");
}
if (destDir.exists() && destDir.isDirectory() == false) {
throw new IllegalArgumentException("Destination '" + destDir + "' is not a directory");
}
copyFile(srcFile, new File(destDir, srcFile.getName()), preserveFileDate);
|
public static void | copyURLToFile(java.net.URL source, java.io.File destination)Copies bytes from the URL source to a file
destination . The directories up to destination
will be created if they don't already exist. destination
will be overwritten if it already exists.
InputStream input = source.openStream();
try {
FileOutputStream output = openOutputStream(destination);
try {
IOUtils.copy(input, output);
} finally {
IOUtils.closeQuietly(output);
}
} finally {
IOUtils.closeQuietly(input);
}
|
public static void | deleteDirectory(java.io.File directory)Deletes a directory recursively.
if (!directory.exists()) {
return;
}
cleanDirectory(directory);
if (!directory.delete()) {
String message =
"Unable to delete directory " + directory + ".";
throw new IOException(message);
}
|
private static void | deleteDirectoryOnExit(java.io.File directory)Schedules a directory recursively for deletion on JVM exit.
if (!directory.exists()) {
return;
}
cleanDirectoryOnExit(directory);
directory.deleteOnExit();
|
public static boolean | deleteQuietly(java.io.File file)Deletes a file, never throwing an exception. If file is a directory, delete it and all sub-directories.
The difference between File.delete() and this method are:
- A directory to be deleted does not have to be empty.
- No exceptions are thrown when a file or directory cannot be deleted.
if (file == null) {
return false;
}
try {
if (file.isDirectory()) {
cleanDirectory(file);
}
} catch (Exception e) {
}
try {
return file.delete();
} catch (Exception e) {
return false;
}
|
private static void | doCopyDirectory(java.io.File srcDir, java.io.File destDir, java.io.FileFilter filter, boolean preserveFileDate, java.util.List exclusionList)Internal copy directory method.
if (destDir.exists()) {
if (destDir.isDirectory() == false) {
throw new IOException("Destination '" + destDir + "' exists but is not a directory");
}
} else {
if (destDir.mkdirs() == false) {
throw new IOException("Destination '" + destDir + "' directory cannot be created");
}
if (preserveFileDate) {
destDir.setLastModified(srcDir.lastModified());
}
}
if (destDir.canWrite() == false) {
throw new IOException("Destination '" + destDir + "' cannot be written to");
}
// recurse
File[] files = filter == null ? srcDir.listFiles() : srcDir.listFiles(filter);
if (files == null) { // null if security restricted
throw new IOException("Failed to list contents of " + srcDir);
}
for (int i = 0; i < files.length; i++) {
File copiedFile = new File(destDir, files[i].getName());
if (exclusionList == null || !exclusionList.contains(files[i].getCanonicalPath())) {
if (files[i].isDirectory()) {
doCopyDirectory(files[i], copiedFile, filter, preserveFileDate, exclusionList);
} else {
doCopyFile(files[i], copiedFile, preserveFileDate);
}
}
}
|
private static void | doCopyFile(java.io.File srcFile, java.io.File destFile, boolean preserveFileDate)Internal copy file method.
if (destFile.exists() && destFile.isDirectory()) {
throw new IOException("Destination '" + destFile + "' exists but is a directory");
}
FileInputStream input = new FileInputStream(srcFile);
try {
FileOutputStream output = new FileOutputStream(destFile);
try {
IOUtils.copy(input, output);
} finally {
IOUtils.closeQuietly(output);
}
} finally {
IOUtils.closeQuietly(input);
}
if (srcFile.length() != destFile.length()) {
throw new IOException("Failed to copy full contents from '" +
srcFile + "' to '" + destFile + "'");
}
if (preserveFileDate) {
destFile.setLastModified(srcFile.lastModified());
}
|
public static void | forceDelete(java.io.File file)Deletes a file. If file is a directory, delete it and all sub-directories.
The difference between File.delete() and this method are:
- A directory to be deleted does not have to be empty.
- You get exceptions when a file or directory cannot be deleted.
(java.io.File methods returns a boolean)
if (file.isDirectory()) {
deleteDirectory(file);
} else {
boolean filePresent = file.exists();
if (!file.delete()) {
if (!filePresent){
throw new FileNotFoundException("File does not exist: " + file);
}
String message =
"Unable to delete file: " + file;
throw new IOException(message);
}
}
|
public static void | forceDeleteOnExit(java.io.File file)Schedules a file to be deleted when JVM exits.
If file is directory delete it and all sub-directories.
if (file.isDirectory()) {
deleteDirectoryOnExit(file);
} else {
file.deleteOnExit();
}
|
public static void | forceMkdir(java.io.File directory)Makes a directory, including any necessary but nonexistent parent
directories. If there already exists a file with specified name or
the directory cannot be created then an exception is thrown.
if (directory.exists()) {
if (directory.isFile()) {
String message =
"File "
+ directory
+ " exists and is "
+ "not a directory. Unable to create directory.";
throw new IOException(message);
}
} else {
if (!directory.mkdirs()) {
String message =
"Unable to create directory " + directory;
throw new IOException(message);
}
}
|
private static void | innerListFiles(java.util.Collection files, java.io.File directory, org.apache.commons.io.filefilter.IOFileFilter filter)Finds files within a given directory (and optionally its
subdirectories). All files found are filtered by an IOFileFilter.
File[] found = directory.listFiles((FileFilter) filter);
if (found != null) {
for (int i = 0; i < found.length; i++) {
if (found[i].isDirectory()) {
innerListFiles(files, found[i], filter);
} else {
files.add(found[i]);
}
}
}
|
public static boolean | isFileNewer(java.io.File file, java.io.File reference)Tests if the specified File is newer than the reference
File .
if (reference == null) {
throw new IllegalArgumentException("No specified reference file");
}
if (!reference.exists()) {
throw new IllegalArgumentException("The reference file '"
+ file + "' doesn't exist");
}
return isFileNewer(file, reference.lastModified());
|
public static boolean | isFileNewer(java.io.File file, java.util.Date date)Tests if the specified File is newer than the specified
Date .
if (date == null) {
throw new IllegalArgumentException("No specified date");
}
return isFileNewer(file, date.getTime());
|
public static boolean | isFileNewer(java.io.File file, long timeMillis)Tests if the specified File is newer than the specified
time reference.
if (file == null) {
throw new IllegalArgumentException("No specified file");
}
if (!file.exists()) {
return false;
}
return file.lastModified() > timeMillis;
|
public static boolean | isFileOlder(java.io.File file, java.io.File reference)Tests if the specified File is older than the reference
File .
if (reference == null) {
throw new IllegalArgumentException("No specified reference file");
}
if (!reference.exists()) {
throw new IllegalArgumentException("The reference file '"
+ file + "' doesn't exist");
}
return isFileOlder(file, reference.lastModified());
|
public static boolean | isFileOlder(java.io.File file, java.util.Date date)Tests if the specified File is older than the specified
Date .
if (date == null) {
throw new IllegalArgumentException("No specified date");
}
return isFileOlder(file, date.getTime());
|
public static boolean | isFileOlder(java.io.File file, long timeMillis)Tests if the specified File is older than the specified
time reference.
if (file == null) {
throw new IllegalArgumentException("No specified file");
}
if (!file.exists()) {
return false;
}
return file.lastModified() < timeMillis;
|
public static java.util.Iterator | iterateFiles(java.io.File directory, java.lang.String[] extensions, boolean recursive)Allows iteration over the files in a given directory (and optionally
its subdirectories) which match an array of extensions. This method
is based on {@link #listFiles(File, String[], boolean)}.
return listFiles(directory, extensions, recursive).iterator();
|
public static java.util.Iterator | iterateFiles(java.io.File directory, org.apache.commons.io.filefilter.IOFileFilter fileFilter, org.apache.commons.io.filefilter.IOFileFilter dirFilter)Allows iteration over the files in given directory (and optionally
its subdirectories).
All files found are filtered by an IOFileFilter. This method is
based on {@link #listFiles(File, IOFileFilter, IOFileFilter)}.
return listFiles(directory, fileFilter, dirFilter).iterator();
|
public static org.apache.commons.io.LineIterator | lineIterator(java.io.File file, java.lang.String encoding)Returns an Iterator for the lines in a File .
This method opens an InputStream for the file.
When you have finished with the iterator you should close the stream
to free internal resources. This can be done by calling the
{@link LineIterator#close()} or
{@link LineIterator#closeQuietly(LineIterator)} method.
The recommended usage pattern is:
LineIterator it = FileUtils.lineIterator(file, "UTF-8");
try {
while (it.hasNext()) {
String line = it.nextLine();
/// do something with line
}
} finally {
LineIterator.closeQuietly(iterator);
}
If an exception occurs during the creation of the iterator, the
underlying stream is closed.
InputStream in = null;
try {
in = openInputStream(file);
return IOUtils.lineIterator(in, encoding);
} catch (IOException ex) {
IOUtils.closeQuietly(in);
throw ex;
} catch (RuntimeException ex) {
IOUtils.closeQuietly(in);
throw ex;
}
|
public static org.apache.commons.io.LineIterator | lineIterator(java.io.File file)Returns an Iterator for the lines in a File using the default encoding for the VM.
return lineIterator(file, null);
|
public static java.util.Collection | listFiles(java.io.File directory, java.lang.String[] extensions, boolean recursive)Finds files within a given directory (and optionally its subdirectories)
which match an array of extensions.
IOFileFilter filter;
if (extensions == null) {
filter = TrueFileFilter.INSTANCE;
} else {
String[] suffixes = toSuffixes(extensions);
filter = new SuffixFileFilter(suffixes);
}
return listFiles(directory, filter,
(recursive ? TrueFileFilter.INSTANCE : FalseFileFilter.INSTANCE));
|
public static java.util.Collection | listFiles(java.io.File directory, org.apache.commons.io.filefilter.IOFileFilter fileFilter, org.apache.commons.io.filefilter.IOFileFilter dirFilter)Finds files within a given directory (and optionally its
subdirectories). All files found are filtered by an IOFileFilter.
If your search should recurse into subdirectories you can pass in
an IOFileFilter for directories. You don't need to bind a
DirectoryFileFilter (via logical AND) to this filter. This method does
that for you.
An example: If you want to search through all directories called
"temp" you pass in FileFilterUtils.NameFileFilter("temp")
Another common usage of this method is find files in a directory
tree but ignoring the directories generated CVS. You can simply pass
in FileFilterUtils.makeCVSAware(null) .
if (!directory.isDirectory()) {
throw new IllegalArgumentException(
"Parameter 'directory' is not a directory");
}
if (fileFilter == null) {
throw new NullPointerException("Parameter 'fileFilter' is null");
}
//Setup effective file filter
IOFileFilter effFileFilter = FileFilterUtils.andFileFilter(fileFilter,
FileFilterUtils.notFileFilter(DirectoryFileFilter.INSTANCE));
//Setup effective directory filter
IOFileFilter effDirFilter;
if (dirFilter == null) {
effDirFilter = FalseFileFilter.INSTANCE;
} else {
effDirFilter = FileFilterUtils.andFileFilter(dirFilter,
DirectoryFileFilter.INSTANCE);
}
//Find files
Collection files = new java.util.LinkedList();
innerListFiles(files, directory,
FileFilterUtils.orFileFilter(effFileFilter, effDirFilter));
return files;
|
public static void | moveDirectory(java.io.File srcDir, java.io.File destDir)Moves a directory.
When the destination directory is on another file system, do a "copy and delete".
if (srcDir == null) {
throw new NullPointerException("Source must not be null");
}
if (destDir == null) {
throw new NullPointerException("Destination must not be null");
}
if (!srcDir.exists()) {
throw new FileNotFoundException("Source '" + srcDir + "' does not exist");
}
if (!srcDir.isDirectory()) {
throw new IOException("Source '" + srcDir + "' is not a directory");
}
if (destDir.exists()) {
throw new IOException("Destination '" + destDir + "' already exists");
}
boolean rename = srcDir.renameTo(destDir);
if (!rename) {
copyDirectory( srcDir, destDir );
deleteDirectory( srcDir );
if (srcDir.exists()) {
throw new IOException("Failed to delete original directory '" + srcDir +
"' after copy to '" + destDir + "'");
}
}
|
public static void | moveDirectoryToDirectory(java.io.File src, java.io.File destDir, boolean createDestDir)Moves a directory to another directory.
if (src == null) {
throw new NullPointerException("Source must not be null");
}
if (destDir == null) {
throw new NullPointerException("Destination directory must not be null");
}
if (!destDir.exists() && createDestDir) {
destDir.mkdirs();
}
if (!destDir.exists()) {
throw new FileNotFoundException("Destination directory '" + destDir +
"' does not exist [createDestDir=" + createDestDir +"]");
}
if (!destDir.isDirectory()) {
throw new IOException("Destination '" + destDir + "' is not a directory");
}
moveDirectory(src, new File(destDir, src.getName()));
|
public static void | moveFile(java.io.File srcFile, java.io.File destFile)Moves a file.
When the destination file is on another file system, do a "copy and delete".
if (srcFile == null) {
throw new NullPointerException("Source must not be null");
}
if (destFile == null) {
throw new NullPointerException("Destination must not be null");
}
if (!srcFile.exists()) {
throw new FileNotFoundException("Source '" + srcFile + "' does not exist");
}
if (srcFile.isDirectory()) {
throw new IOException("Source '" + srcFile + "' is a directory");
}
if (destFile.exists()) {
throw new IOException("Destination '" + destFile + "' already exists");
}
if (destFile.isDirectory()) {
throw new IOException("Destination '" + destFile + "' is a directory");
}
boolean rename = srcFile.renameTo(destFile);
if (!rename) {
copyFile( srcFile, destFile );
if (!srcFile.delete()) {
FileUtils.deleteQuietly(destFile);
throw new IOException("Failed to delete original file '" + srcFile +
"' after copy to '" + destFile + "'");
}
}
|
public static void | moveFileToDirectory(java.io.File srcFile, java.io.File destDir, boolean createDestDir)Moves a file to a directory.
if (srcFile == null) {
throw new NullPointerException("Source must not be null");
}
if (destDir == null) {
throw new NullPointerException("Destination directory must not be null");
}
if (!destDir.exists() && createDestDir) {
destDir.mkdirs();
}
if (!destDir.exists()) {
throw new FileNotFoundException("Destination directory '" + destDir +
"' does not exist [createDestDir=" + createDestDir +"]");
}
if (!destDir.isDirectory()) {
throw new IOException("Destination '" + destDir + "' is not a directory");
}
moveFile(srcFile, new File(destDir, srcFile.getName()));
|
public static void | moveToDirectory(java.io.File src, java.io.File destDir, boolean createDestDir)Moves a file or directory to the destination directory.
When the destination is on another file system, do a "copy and delete".
if (src == null) {
throw new NullPointerException("Source must not be null");
}
if (destDir == null) {
throw new NullPointerException("Destination must not be null");
}
if (!src.exists()) {
throw new FileNotFoundException("Source '" + src + "' does not exist");
}
if (src.isDirectory()) {
moveDirectoryToDirectory(src, destDir, createDestDir);
} else {
moveFileToDirectory(src, destDir, createDestDir);
}
|
public static java.io.FileInputStream | openInputStream(java.io.File file)Opens a {@link FileInputStream} for the specified file, providing better
error messages than simply calling new 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.
//-----------------------------------------------------------------------
if (file.exists()) {
if (file.isDirectory()) {
throw new IOException("File '" + file + "' exists but is a directory");
}
if (file.canRead() == false) {
throw new IOException("File '" + file + "' cannot be read");
}
} else {
throw new FileNotFoundException("File '" + file + "' does not exist");
}
return new FileInputStream(file);
|
public static java.io.FileOutputStream | openOutputStream(java.io.File file)Opens a {@link FileOutputStream} for the specified file, checking and
creating the parent directory if it does not exist.
At the end of the method either the stream will be successfully opened,
or an exception will have been thrown.
The parent directory will be created if it does not exist.
The file will be created if it does not exist.
An exception is thrown if the file object exists but is a directory.
An exception is thrown if the file exists but cannot be written to.
An exception is thrown if the parent directory cannot be created.
if (file.exists()) {
if (file.isDirectory()) {
throw new IOException("File '" + file + "' exists but is a directory");
}
if (file.canWrite() == false) {
throw new IOException("File '" + file + "' cannot be written to");
}
} else {
File parent = file.getParentFile();
if (parent != null && parent.exists() == false) {
if (parent.mkdirs() == false) {
throw new IOException("File '" + file + "' could not be created");
}
}
}
return new FileOutputStream(file);
|
public static byte[] | readFileToByteArray(java.io.File file)Reads the contents of a file into a byte array.
The file is always closed.
InputStream in = null;
try {
in = openInputStream(file);
return IOUtils.toByteArray(in);
} finally {
IOUtils.closeQuietly(in);
}
|
public static java.lang.String | readFileToString(java.io.File file, java.lang.String encoding)Reads the contents of a file into a String.
The file is always closed.
InputStream in = null;
try {
in = openInputStream(file);
return IOUtils.toString(in, encoding);
} finally {
IOUtils.closeQuietly(in);
}
|
public static java.lang.String | readFileToString(java.io.File file)Reads the contents of a file into a String using the default encoding for the VM.
The file is always closed.
return readFileToString(file, null);
|
public static java.util.List | readLines(java.io.File file, java.lang.String encoding)Reads the contents of a file line by line to a List of Strings.
The file is always closed.
InputStream in = null;
try {
in = openInputStream(file);
return IOUtils.readLines(in, encoding);
} finally {
IOUtils.closeQuietly(in);
}
|
public static java.util.List | readLines(java.io.File file)Reads the contents of a file line by line to a List of Strings using the default encoding for the VM.
The file is always closed.
return readLines(file, null);
|
public static long | sizeOfDirectory(java.io.File directory)Counts the size of a directory recursively (sum of the length of all files).
if (!directory.exists()) {
String message = directory + " does not exist";
throw new IllegalArgumentException(message);
}
if (!directory.isDirectory()) {
String message = directory + " is not a directory";
throw new IllegalArgumentException(message);
}
long size = 0;
File[] files = directory.listFiles();
if (files == null) { // null if security restricted
return 0L;
}
for (int i = 0; i < files.length; i++) {
File file = files[i];
if (file.isDirectory()) {
size += sizeOfDirectory(file);
} else {
size += file.length();
}
}
return size;
|
public static java.io.File | toFile(java.net.URL url)Convert from a URL to a File .
From version 1.1 this method will decode the URL.
Syntax such as file:///my%20docs/file.txt will be
correctly decoded to /my docs/file.txt .
if (url == null || !url.getProtocol().equals("file")) {
return null;
} else {
String filename = url.getFile().replace('/", File.separatorChar);
int pos =0;
while ((pos = filename.indexOf('%", pos)) >= 0) {
if (pos + 2 < filename.length()) {
String hexStr = filename.substring(pos + 1, pos + 3);
char ch = (char) Integer.parseInt(hexStr, 16);
filename = filename.substring(0, pos) + ch + filename.substring(pos + 3);
}
}
return new File(filename);
}
|
public static java.io.File[] | toFiles(java.net.URL[] urls)Converts each of an array of URL to a File .
Returns an array of the same size as the input.
If the input is null , an empty array is returned.
If the input contains null , the output array contains null at the same
index.
This method will decode the URL.
Syntax such as file:///my%20docs/file.txt will be
correctly decoded to /my docs/file.txt .
if (urls == null || urls.length == 0) {
return EMPTY_FILE_ARRAY;
}
File[] files = new File[urls.length];
for (int i = 0; i < urls.length; i++) {
URL url = urls[i];
if (url != null) {
if (url.getProtocol().equals("file") == false) {
throw new IllegalArgumentException(
"URL could not be converted to a File: " + url);
}
files[i] = toFile(url);
}
}
return files;
|
private static java.lang.String[] | toSuffixes(java.lang.String[] extensions)Converts an array of file extensions to suffixes for use
with IOFileFilters.
String[] suffixes = new String[extensions.length];
for (int i = 0; i < extensions.length; i++) {
suffixes[i] = "." + extensions[i];
}
return suffixes;
|
public static java.net.URL[] | toURLs(java.io.File[] files)Converts each of an array of File to a URL .
Returns an array of the same size as the input.
URL[] urls = new URL[files.length];
for (int i = 0; i < urls.length; i++) {
urls[i] = files[i].toURL();
}
return urls;
|
public static void | touch(java.io.File file)Implements the same behaviour as the "touch" utility on Unix. It creates
a new file with size 0 or, if the file exists already, it is opened and
closed without modifying it, but updating the file date and time.
NOTE: As from v1.3, this method throws an IOException if the last
modified date of the file cannot be set. Also, as from v1.3 this method
creates parent directories if they do not exist.
if (!file.exists()) {
OutputStream out = openOutputStream(file);
IOUtils.closeQuietly(out);
}
boolean success = file.setLastModified(System.currentTimeMillis());
if (!success) {
throw new IOException("Unable to set the last modification time for " + file);
}
|
public static boolean | waitFor(java.io.File file, int seconds)Waits for NFS to propagate a file creation, imposing a timeout.
This method repeatedly tests {@link File#exists()} until it returns
true up to the maximum time specified in seconds.
int timeout = 0;
int tick = 0;
while (!file.exists()) {
if (tick++ >= 10) {
tick = 0;
if (timeout++ > seconds) {
return false;
}
}
try {
Thread.sleep(100);
} catch (InterruptedException ignore) {
// ignore exception
} catch (Exception ex) {
break;
}
}
return true;
|
public static void | writeByteArrayToFile(java.io.File file, byte[] data)Writes a byte array to a file creating the file if it does not exist.
NOTE: As from v1.3, the parent directories of the file will be created
if they do not exist.
OutputStream out = null;
try {
out = openOutputStream(file);
out.write(data);
} finally {
IOUtils.closeQuietly(out);
}
|
public static void | writeLines(java.io.File file, java.lang.String encoding, java.util.Collection lines)Writes the toString() value of each item in a collection to
the specified File line by line.
The specified character encoding and the default line ending will be used.
NOTE: As from v1.3, the parent directories of the file will be created
if they do not exist.
writeLines(file, encoding, lines, null);
|
public static void | writeLines(java.io.File file, java.util.Collection lines)Writes the toString() value of each item in a collection to
the specified File line by line.
The default VM encoding and the default line ending will be used.
writeLines(file, null, lines, null);
|
public static void | writeLines(java.io.File file, java.lang.String encoding, java.util.Collection lines, java.lang.String lineEnding)Writes the toString() value of each item in a collection to
the specified File line by line.
The specified character encoding and the line ending will be used.
NOTE: As from v1.3, the parent directories of the file will be created
if they do not exist.
OutputStream out = null;
try {
out = openOutputStream(file);
IOUtils.writeLines(lines, lineEnding, out, encoding);
} finally {
IOUtils.closeQuietly(out);
}
|
public static void | writeLines(java.io.File file, java.util.Collection lines, java.lang.String lineEnding)Writes the toString() value of each item in a collection to
the specified File line by line.
The default VM encoding and the specified line ending will be used.
writeLines(file, null, lines, lineEnding);
|
public static void | writeStringToFile(java.io.File file, java.lang.String data, java.lang.String encoding)Writes a String to a file creating the file if it does not exist.
NOTE: As from v1.3, the parent directories of the file will be created
if they do not exist.
OutputStream out = null;
try {
out = openOutputStream(file);
IOUtils.write(data, out, encoding);
} finally {
IOUtils.closeQuietly(out);
}
|
public static void | writeStringToFile(java.io.File file, java.lang.String data)Writes a String to a file creating the file if it does not exist using the default encoding for the VM.
writeStringToFile(file, data, null);
|