public class FileUtilities extends Object
| Modifier and Type | Class and Description |
|---|---|
static class |
FileUtilities.RetryPolicy
Specifies a policy about what to do if a file action (e.g.
|
static class |
FileUtilities.TargetExistsAction
The action to take when moving/copying files and the target already exists
|
| Modifier and Type | Method and Description |
|---|---|
static void |
copyDirectory(File sourceDirectory,
File destinationDirectory,
boolean overwrite,
ProgressListener progressListener)
Recursively copies the entire contents of one directory to another.
|
static void |
copyFile(File sourceFile,
File destinationFile,
FileUtilities.TargetExistsAction targetExistsAction,
ProgressListener progressListener)
Copies the contents of a file to another file
If canceled in the middle of the copy (so that the destination file is partially written), the
destination file will be deleted.
|
static boolean |
createHardLink(File existingFile,
File newFile)
Creates a file system hard link.
|
static File |
createTempDir(boolean deleteDirectoryOnceItIsNoLongerReferenced)
Creates a temporary directory.
|
static File |
createTempFile(String fileName,
boolean deleteParentFolderWhenFileIsNoLongerReferenced)
Returns a temporary file with the given name.
|
static File |
createTempFile(String prefix,
String suffix)
Deprecated.
use
createTempFile(String, String, boolean) instead. |
static File |
createTempFile(String prefix,
String suffix,
boolean deleteFileOnceItIsNoLongerReferenced)
Creates a temporary file as specified by
File.createTempFile(String, String, java.io.File). |
static boolean |
deleteDirectory(File path,
ProgressListener progressListener)
Recursively deletes a directory.
|
static boolean |
deleteFileOrDirectory(File file,
boolean retryIfNecessary)
Deletes the given file or directory.
|
static boolean |
deleteFileOrDirectory(File file,
FileUtilities.RetryPolicy retryPolicy)
Deletes the given file or directory.
|
static String |
getCanonicalOrAbsolutePath(File file)
Returns the result of calling
File.getCanonicalPath(), or if that fails,
returns the result of calling File.getAbsolutePath() . |
static String |
getFileNameExtension(File file)
Get the extension of a file name.
|
static String |
getFileNameWithoutExtension(File file)
Get the name of a file, excluding its path, excluding its extension and excluding the '.' prior to its extension.
|
static long |
getFileOrFolderSize(File file,
ProgressListener progressListener)
If file is not a directory this returns
File.length(), if file is a directory this recurses
through all files in the directory and sub directories to return the sum of File.length()s. |
static String |
getLegalFileName(String fileName,
String illegalCharacterReplacement)
Get a file name that is guaranteed to be legal by replacing all characters in the given string that are not
allowed in a file name with the given replacement.
|
static File |
getResourceForClass(Class cl,
String resourceName)
for grabbing resources based on a directory hirarchy identical to the one that the class
cl is
found in. |
static String |
getTextFromFile(File file)
Reads the entire contents of a file into a string.
|
static File |
getUserSelectedFile(String title,
FilenameFilter filter,
int fileSelectionType)
Displays a file open dialog to the user (a Java dialog on windows and unix, a Mac dialog on MacOS), and returns the file that the user selected (or null if they cancelled)
|
static File |
getUserSelectedSaveFile(String approveButtonText,
String title,
String defaultFileName,
String defaultFilterExtension)
Displays a file save dialog to the user (a Java dialog on windows and unix, a Mac dialog on MacOS), and returns the file that the user selected (or null if they cancelled)
|
static String |
isFileNameAllowed(String fileName)
Will check a filename for validity on all platforms supported by Geneious.
|
static FileInputStream |
newFileInputStreamWithRetry(File file)
Attempts to create a new FileInputStream, but if it fails, retries a few times until it succeeds.
|
static FileOutputStream |
newFileOutputStreamWithRetry(File file)
Attempts to create a new FileOutputStream, but if it fails with a FileNotFoundException, retries a few times until it succeeds.
|
static RandomAccessFile |
newRandomAccessFileWithRetry(File file,
String mode)
Attempts to create a new RandomAccessFile, but if it fails, retries a few times until it succeeds.
|
static boolean |
renameToWithRetry(File source,
File destination)
Similar to
File.renameTo(java.io.File) except that
if the rename fails, we retry a few times (performing garbage
collections and sleeping briefly between attempts) if necessary
until it succeeds, potentially waiting for up to approximately 1 second. |
static void |
setExecutableFlags(File file)
Set the executable flag on a file, or do nothing if the OS does not support this behaviour
Since Geneious 5.1.2 will accept a directory as argument to world execute on the entire directory tree
|
static void |
unzip(File zipFile,
File destinationDirectory,
ProgressListener progressListener)
Extract a zip file.
|
static void |
writeTextToFile(File file,
String text)
Wrties the given text to a file, overwriting any existing contents of the file.
|
static void |
zip(File fileOrDirectory,
File zipFile,
boolean includeRootDirectory,
ProgressListener progressListener)
Create a compressed zip containing a file or directory.
|
static void |
zipWithoutCompression(File fileOrDirectory,
File zipFile,
boolean includeRootDirectory,
ProgressListener progressListener)
Create a zip containing a file or directory without any compression.
|
public static String isFileNameAllowed(String fileName)
fileName - the name of a file excluding the path. must not be nullpublic static String getLegalFileName(String fileName, String illegalCharacterReplacement)
fileName - file name to make legalillegalCharacterReplacement - string to replace every occurrence of an illegal character withfileName if the name was
already legal.public static String getFileNameWithoutExtension(File file)
file - the file to get the name forpublic static String getFileNameExtension(File file)
file - the file to get the extension forpublic static String getTextFromFile(File file) throws IOException
file - the file to loadIOException - if any method calls to the File throw an IOExceptionwriteTextToFile(java.io.File, String),
StringUtilities.getTextFromInputStream(java.io.InputStream,boolean),
StringUtilities.getTextFromReader(java.io.Reader, boolean)public static void writeTextToFile(File file, String text) throws IOException
file - the file to write to.text - the text to write to the fileIOException - if any method calls to the File throw an IOExceptiongetTextFromFile(java.io.File)public static void copyFile(File sourceFile, File destinationFile, FileUtilities.TargetExistsAction targetExistsAction, ProgressListener progressListener) throws IOException
sourceFile - the file to copy the contents fromdestinationFile - the file to copy the contents totargetExistsAction - action to take when the destination file already exists: Fail (throw an IOException),
skip (silently keep the destination file), overwrite (silently copy anyway, overwriting the
destination file)progressListener - a progress listener to notify about progress during the copy and also provide the ability to cancel the copy. If the copy is cancelled, any partially written destination file will be removed. Must not be null, but may be ProgressListener.EMPTY.IOException - if the file cannot be copied for any reason.public static void copyDirectory(File sourceDirectory, File destinationDirectory, boolean overwrite, ProgressListener progressListener) throws IOException
sourceDirectory - the directory to copy the contents ofdestinationDirectory - the directly to copy the contents tooverwrite - true to overwrite files of the same name that exist in the desitination directory.progressListener - ProgressListener to report progress of the copying to. If the progressListener is
canceled, this method does not restore the destination to its original state. Must not be null, but may be ProgressListener.EMPTY.IOException - if the directory cannot be copied for any reason.IllegalArgumentException - if sourceDirectory is not a directory.public static long getFileOrFolderSize(File file, ProgressListener progressListener)
File.length(), if file is a directory this recurses
through all files in the directory and sub directories to return the sum of File.length()s.file - a directory or file to calculate the size ofprogressListener - since this method may potentially take a long time, this may be used to abort this method in which case it returns the total size calculated so far. This method does not report any progress (rather it only reports to the progressListeners message the size calculated so far and uses it for determining whether to cancel). progressListener may be null.public static void zip(File fileOrDirectory, File zipFile, boolean includeRootDirectory, ProgressListener progressListener) throws IOException
fileOrDirectory - a file or directory to be compressedzipFile - the target zip file. will be created if doesn't exist, will be replaced if already existsincludeRootDirectory - true to include fileOrDirectory in the zip file, false to only include the contents of fileOrDirectory. Only applicable when a directory is passed in, ignored otherwise.progressListener - allows canceling and progress reportingIOException - if the zip file couldn't be written for any reasonpublic static void zipWithoutCompression(File fileOrDirectory, File zipFile, boolean includeRootDirectory, ProgressListener progressListener) throws IOException
zip(java.io.File, java.io.File, boolean, jebl.util.ProgressListener)
except much faster and zip file will be larger.fileOrDirectory - a file or directory to be compressedzipFile - the target zip file. will be created if doesn't exist, will be replaced if already existsincludeRootDirectory - true to include fileOrDirectory in the zip file, false to only include the contents of fileOrDirectory. Only applicable when a directory is passed in, ignored otherwise.progressListener - allows canceling and progress reportingIOException - if the zip file couldn't be written for any reasonpublic static void unzip(File zipFile, File destinationDirectory, ProgressListener progressListener) throws IOException
zipFile - the zip file to be extracteddestinationDirectory - the directory to extract the contents of the zip file toprogressListener - allows canceling and progress reportingIOException - if extracted files couldn't be written for any reasonpublic static boolean deleteDirectory(File path, ProgressListener progressListener)
File.delete() this method will remove non-empty directories.path - the directory to deleteprogressListener - ProgressListener to report progress of the deletion to. If the progressListener is
canceled, this method does not restore any already deleted files or sub-directories. Must not be null, but may be ProgressListener.EMPTY.File.delete() contract, this means this method will return false if the directory did not previously exist.public static boolean renameToWithRetry(File source, File destination)
File.renameTo(java.io.File) except that
if the rename fails, we retry a few times (performing garbage
collections and sleeping briefly between attempts) if necessary
until it succeeds, potentially waiting for up to approximately 1 second.
This is a workaround for Java bug 6213298 at http://bugs.sun.com/view_bug.do?bug_id=6213298source - the file or directory to renamedestination - the new name for the source file.true if and only if the renaming succeeded;
false otherwise
(just like File.renameTo(java.io.File) )public static void setExecutableFlags(File file) throws IOException, InterruptedException
file - file or directory to set permissions forInterruptedException - if something interrupts the process setting the permissionsIOException - if something else goes wrongpublic static String getCanonicalOrAbsolutePath(File file)
File.getCanonicalPath(), or if that fails,
returns the result of calling File.getAbsolutePath() .file - the file to get the canonical or absolute path of.File.getCanonicalPath(), or if that fails,
returns the result of calling File.getAbsolutePath() .public static boolean deleteFileOrDirectory(File file, boolean retryIfNecessary)
file - the file or directory to delete.retryIfNecessary - true to retry a few times for up to approximately a second to delete the file if it can't be deleted the first time, performing garbage collection and sleeping briefly between attemptspublic static boolean deleteFileOrDirectory(File file, FileUtilities.RetryPolicy retryPolicy)
file - the file or directory to delete.retryPolicy - if the file can't be deleted, indicates what to do. If it is RetryPolicy.Never returns false. If it is RetryPolicy.Now a few attempts are immediately made to delete the file.
If it is RetryPolicy.Later, this method returns false, the file will be queued, and it will attempts to delete it will be made periodically until successful.public static File getUserSelectedFile(String title, FilenameFilter filter, int fileSelectionType)
title - the title of the file dialogfilter - to filter the files displayed in the dialogfileSelectionType - either JFileChooser.FILES_AND_DIRECTORIES, JFileChooser.FILES_ONLY, or JFileChooser.DIRECTORIES_ONLYpublic static File getUserSelectedSaveFile(String approveButtonText, String title, String defaultFileName, String defaultFilterExtension)
title - the title of the file dialogdefaultFileName - the default name for the file (this will be entered into the file dialog when it first opens)defaultFilterExtension - the default extension for the file filter@Deprecated public static File createTempFile(String prefix, String suffix) throws IOException
createTempFile(String, String, boolean) instead.createTempFile(prefix, suffix, true)IOExceptionpublic static File createTempFile(String prefix, String suffix, boolean deleteFileOnceItIsNoLongerReferenced) throws IOException
File.createTempFile(String, String, java.io.File).
If Geneious is running when this method is invoked, Geneious will supply a temporary directory in the user's data directory
which will have its contents deleted when Geneious is next started.
If Geneious is not running when this method is invoked, the standard system temporary directory is used.
If deleteFileOnceItIsNoLongerReferenced is true, then the returned file will be automatically deleted once the returned File or the String obtained from
File.getPath() or File.toString() are no longer referenced in this JVM. The returned
file will already have had its path canonicalized (via File.getCanonicalPath()) so there is
no need to call that method on the returned file and doing so will not hold a reference to the given file
potentially causing it to be deleted early. No matter what the value of deleteFileOnceItIsNoLongerReferenced, the
file will be deleted if it still exists when the user next starts Geneious. Do not set this to true for files passed to external
command line programs or the file may end up getting deleted before the external command line program accesses it.
The user may change their data directory from preferences while Geneious is running, so plugins should
not assume the path of the returned file to necessarily be the same from separate calls to this method.prefix - - The prefix string to be used in generating the file's name; must be at least three characters longsuffix - - The suffix string to be used in generating the file's name; may be null, in which case the suffix ".tmp" will be useddeleteFileOnceItIsNoLongerReferenced - - see above. use false to make this method behave like File.createTempFile(String, String, java.io.File). WARNING: do not set this to true for files passed to external command line programs or the file may end up getting deleted before the external command line program accesses it.IOException - If a file could not be createdpublic static File createTempFile(String fileName, boolean deleteParentFolderWhenFileIsNoLongerReferenced) throws IOException
createTempFile(String, String, boolean) which only allows specifying the prefix or suffixfileName - the name of the file to returndeleteParentFolderWhenFileIsNoLongerReferenced - true to delete the parent sub-folder and everything in it once this file is no longer referenced.IOException - If a file or directory could not be createdpublic static File createTempDir(boolean deleteDirectoryOnceItIsNoLongerReferenced) throws IOException
File.getPath() or File.toString() are no longer referenced, even if there are still referenced files within that directory. The returned
directory will already have had its path made canonical (via File.getCanonicalPath()) so there is
no need to call that method on the returned file and doing so will not hold a reference to the given directory
potentially causing it to be deleted early. No matter what the value of deleteDirectoryOnceItIsNoLongerReferenced, the
directory will be deleted if it still exists when the user next starts Geneious.
The user may change their data directory from preferences while Geneious is running, so plugins should
not assume the path of the returned directory to necessarily be the same from separate calls to this method.deleteDirectoryOnceItIsNoLongerReferenced - - see above.IOException - If a file could not be createdpublic static boolean createHardLink(File existingFile, File newFile)
newRandomAccessFileWithRetry(java.io.File, String) or newFileInputStreamWithRetry(java.io.File)existingFile - a currently existing file to link tonewFile - the new file to create which should link to the existing filepublic static RandomAccessFile newRandomAccessFileWithRetry(File file, String mode) throws FileNotFoundException
createHardLink(java.io.File, java.io.File)file - the file to openmode - the access mode. See RandomAccessFile.RandomAccessFile(java.io.File, String)FileNotFoundException - if RandomAccessFile.RandomAccessFile(java.io.File, String) still throws a FileNotFoundException after a few attemptspublic static FileInputStream newFileInputStreamWithRetry(File file) throws FileNotFoundException
createHardLink(java.io.File, java.io.File)file - the file to openFileNotFoundException - if FileInputStream.FileInputStream(java.io.File) still throws a FileNotFoundException after a few attemptsnewFileOutputStreamWithRetry(java.io.File)public static FileOutputStream newFileOutputStreamWithRetry(File file) throws FileNotFoundException
createHardLink(java.io.File, java.io.File). This is also useful when trying
to write to a file of the same name that was recently deleted on systems with virus scanners. The virus scanner
may still have the original file open, preventing it from being deleted immediately and causing Windows to deny access to
writing to a new file with the same name. See comments at http://stackoverflow.com/questions/8670317/why-cant-i-create-a-txt-file-after-having-just-deleted-itfile - the file to openFileNotFoundException - if FileOutputStream.FileOutputStream(java.io.File) still throws a FileNotFoundException after a few attemptsnewFileInputStreamWithRetry(java.io.File)public static File getResourceForClass(Class cl, String resourceName)
cl is
found in.cl - for example a GeneiousPlugin subclassresourceName - for example a file needed by the pluginIllegalStateException - if the resource is not found.