Class FileUtilities
-
Field Summary
-
Method Summary
Modifier and TypeMethodDescriptionstatic File
checkedMkdir
(File dir) Ensures the specified leaf directory exists.static File
checkedMkdirs
(File dir) Ensures the specified full directory path exists, creating any missing directories as needed.static final int
copyDir
(File originalDir, File copyDir, TaskMonitor monitor) This is the same as callingcopyDir(File, File, FileFilter, TaskMonitor)
with aFileFilter
that accepts all files.static final int
copyDir
(File originalDir, File copyDir, FileFilter filter, TaskMonitor monitor) Copies the contents oforiginalDir
tocopyDir
.static final void
copyFile
(ResourceFile fromFile, ResourceFile toFile, TaskMonitor monitor) Copy the fromFile contents to the toFile.static final void
copyFile
(ResourceFile fromFile, File toFile, boolean append, TaskMonitor monitor) Copy the fromFile contents to the toFile.static final long
copyFile
(File fromFile, File toFile, boolean append, TaskMonitor monitor) Copy the fromFile contents to the toFile.static final void
copyFileToStream
(File fromFile, OutputStream out, TaskMonitor monitor) Copy the contents of the specified fromFile to the out stream.static final long
copyStreamToFile
(InputStream in, File toFile, boolean append, TaskMonitor monitor) Copy the in stream to the toFile.static long
copyStreamToStream
(InputStream in, OutputStream out, TaskMonitor monitor) Copy thein
stream to theout
stream.static boolean
Ensures the specified leaf directory exists.static final boolean
Delete a file or directory and all of its contentsstatic final boolean
deleteDir
(File dir, TaskMonitor monitor) Delete a directory and all of its contentsstatic boolean
Delete a file or directory and all of its contentsstatic boolean
directoryExistsAndIsNotEmpty
(File directory) Returns true if the give file is not null, exists, is a directory and contains files.static boolean
directoryIsEmpty
(File directory) Returns true if the given file is not null, exits, is a directory and has no files.static boolean
static FileResolutionResult
Returns true if a file exists on disk and has a case that matches the filesystem.static FileResolutionResult
existsAndIsCaseDependent
(File file) Returns true if a file exists on disk and has a case that matches the filesystem.static void
forEachFile
(ResourceFile resourceFile, Consumer<ResourceFile> consumer) A convenience method to list the contents of the given directory path and pass each to the given consumer.static void
forEachFile
(File resourceFile, Consumer<File> consumer) A convenience method to list the contents of the given directory path and pass each to the given consumer.static void
forEachFile
(Path path, Consumer<Path> consumer) A convenience method to list the contents of the given directory path and pass each to the given consumer.static String
formatLength
(long length) Returns a human readable string representing the length of something in bytes.static final byte[]
getBytesFromFile
(ResourceFile sourceFile) Return an array of bytes read from the given file.static final byte[]
getBytesFromFile
(ResourceFile sourceFile, long offset, long length) Return an array of bytes read from the sourceFile, starting at the given offsetstatic final byte[]
getBytesFromFile
(File sourceFile) Return an array of bytes read from the given file.static final byte[]
getBytesFromFile
(File sourceFile, long offset, long length) Return an array of bytes read from the sourceFile, starting at the given offsetstatic byte[]
Reads the bytes from the stream into a byte arraystatic byte[]
getBytesFromStream
(InputStream inputStream, int expectedLength) Reads the number of bytes indicated by the expectedLength from the input stream and returns them in a byte array.getLines
(ResourceFile file) Returns all of the lines in the file without any newline characters.Returns all of the lines in theBufferedReader
without any newline characters.Returns all of the lines in the file without any newline charactersgetLines
(InputStream is) Returns all of the lines in the givenInputStream
without any newline characters.Returns all of the lines in the BufferedReader without any newline characters.getLinesQuietly
(ResourceFile file) Returns all of the lines in the file without any newline characters.static String
getPrettySize
(File file) Returns the size of the given file as a human readable String.static String
Returns all of the text in the givenFile
.static String
getText
(InputStream is) Returns all of the text in the givenInputStream
.static boolean
static boolean
isPathContainedWithin
(File potentialParentFile, File otherFile) Returns true if the givenpotentialParentFile
is the parent path of the givenotherFile
, or if the two file paths point to the same path.static boolean
isPathContainedWithin
(Collection<ResourceFile> potentialParents, ResourceFile otherFile) Returns true if any of the givenpotentialParents
is the parent path of or has the same path as the givenotherFile
.static boolean
Make all directories in the full directory path specified.static void
openNative
(File file) Uses theDesktop
API to open the specified file using the user's operating system's native widgets (ie.pathToParts
(String path) static String
relativizePath
(ResourceFile f1, ResourceFile f2) Return the relative path string of one resource file in another.static String
relativizePath
(File f1, File f2) Returns the portion of the second file that trails the full path of the first file.static File
Ensures the specifiedFile
points to a valid existing file, regardless of case match of the file's name.static File
resolveFileCaseSensitive
(File caseSensitiveFile) Ensures that the specifiedFile
param points to a file on the filesystem with a filename that has the exact same character case as the filename portion of the specified File.static void
Sets the given file (or directory) to readable and writable by only the owner.static void
writeBytes
(File file, byte[] bytes) Writes an array of bytes to a file.static void
writeLinesToFile
(File file, List<String> lines) Writes the given list of Strings to the file, separating each by a newline character.static void
writeStringToFile
(File file, String s) Writes the given String to the specifiedFile
.
-
Field Details
-
IO_BUFFER_SIZE
public static final int IO_BUFFER_SIZE- See Also:
-
-
Method Details
-
directoryExistsAndIsNotEmpty
Returns true if the give file is not null, exists, is a directory and contains files.- Parameters:
directory
- the directory to test- Returns:
- true if the give file is not null, exists, is a directory and contains files.
- See Also:
-
directoryIsEmpty
Returns true if the given file is not null, exits, is a directory and has no files.- Parameters:
directory
- the directory to test for emptiness- Returns:
- true if the given file is a directory and has not files.
-
getBytesFromFile
Return an array of bytes read from the given file.- Parameters:
sourceFile
- the source file- Returns:
- the bytes
- Throws:
IOException
- if the file could not be accessed
-
getBytesFromFile
public static final byte[] getBytesFromFile(File sourceFile, long offset, long length) throws IOException Return an array of bytes read from the sourceFile, starting at the given offset- Parameters:
sourceFile
- file to read fromoffset
- offset into the file to begin readinglength
- size of returned array of bytes- Returns:
- array of bytes, size length
- Throws:
IOException
- thrown if there was a problem accessing the file or if there weren't at leastlength
bytes read.
-
getBytesFromFile
Return an array of bytes read from the given file.- Parameters:
sourceFile
- the source file- Returns:
- the bytes
- Throws:
IOException
- if the file could not be accessed
-
writeBytes
Writes an array of bytes to a file.- Parameters:
file
- the file to write tobytes
- the array of bytes to write- Throws:
FileNotFoundException
- thrown if the file path is invalidIOException
- thrown if the file can't be written to.
-
getBytesFromFile
public static final byte[] getBytesFromFile(ResourceFile sourceFile, long offset, long length) throws IOException Return an array of bytes read from the sourceFile, starting at the given offset- Parameters:
sourceFile
- file to read fromoffset
- offset into the file to begin readinglength
- size of returned array of bytes- Returns:
- array of bytes, size length
- Throws:
IOException
- thrown if there was a problem accessing the file or if there weren't at leastlength
bytes read.
-
getBytesFromStream
Reads the bytes from the stream into a byte array- Parameters:
is
- the input stream to read- Returns:
- a byte[] containing the bytes from the stream.
- Throws:
IOException
- if an I/O error occurs reading
-
getBytesFromStream
public static byte[] getBytesFromStream(InputStream inputStream, int expectedLength) throws IOException Reads the number of bytes indicated by the expectedLength from the input stream and returns them in a byte array.- Parameters:
inputStream
- the input streamexpectedLength
- the number of bytes to be read- Returns:
- an array of bytes, that is the expectedLength, that was read from the stream.
- Throws:
IOException
- if the "expectedLength" number of bytes can't be read from the input stream.
-
copyFile
public static final long copyFile(File fromFile, File toFile, boolean append, TaskMonitor monitor) throws IOException Copy the fromFile contents to the toFile. The toFile will be overwritten or created.- Parameters:
fromFile
- source filetoFile
- destination fileappend
- if true and the file exists, the fromFile contents will be appended to the toFile.monitor
- if specified the progress will be reset and will advance to 100% when the copy is complete.- Returns:
- number of bytes copied from source file to destination file
- Throws:
IOException
- thrown if there was a problem accessing the files
-
copyFile
public static final void copyFile(ResourceFile fromFile, File toFile, boolean append, TaskMonitor monitor) throws IOException Copy the fromFile contents to the toFile.- Parameters:
fromFile
- source filetoFile
- destination fileappend
- if true and the file exists, the fromFile contents will be appended to the toFile.monitor
- if specified the progress will be reset and will advance to 100% when the copy is complete.- Throws:
IOException
- thrown if there was a problem accessing the files
-
copyFile
public static final void copyFile(ResourceFile fromFile, ResourceFile toFile, TaskMonitor monitor) throws IOException Copy the fromFile contents to the toFile. The toFile will be overwritten or created.- Parameters:
fromFile
- source filetoFile
- destination filemonitor
- if specified the progress will be reset and will advance to 100% when the copy is complete.- Throws:
IOException
- thrown if there was a problem accessing the files
-
createDir
Ensures the specified leaf directory exists.Does not create any missing parent directories. See
mkdirs(File)
instead.Takes into account race conditions with external threads/processes creating the same directory at the same time.
- Parameters:
dir
- The directory to create.- Returns:
- True If the directory exists when this method completes; otherwise, false.
-
mkdirs
Make all directories in the full directory path specified. This is a replacement for the File.mkdirs() which fails due to a problem with the File.exists() method with remote file systems on Windows. After renaming a directory, the exists() method frequently reports the old directory as still existing. In the case of File.mkdirs() the recreation of the old directory would fail. The File.mkdir() method does not perform this check.- Parameters:
dir
- directory path to be created- Returns:
- True If the directory exists when this method completes; otherwise, false.
-
checkedMkdir
Ensures the specified leaf directory exists.Throws an
IOException
if there is any problem while creating the directory.Does not create any missing parent directories. See
checkedMkdirs(File)
instead.Takes into account race conditions with external threads/processes creating the same directory at the same time.
- Parameters:
dir
- The directory to create.- Returns:
- a reference to the same
File
instance that was passed in. - Throws:
IOException
- if there was a failure when creating the directory (ie. the parent directory did not exist or other issue).
-
checkedMkdirs
Ensures the specified full directory path exists, creating any missing directories as needed.Throws an
IOException
if there is any problem while creating the directory.Uses
createDir(File)
to create new directories (which handles race conditions if other processes are also trying to create the same directory).- Parameters:
dir
- directory path to be created- Returns:
- a reference to the same
File
instance that was passed in. - Throws:
IOException
- if there was a failure when creating a directory.
-
deleteDir
Delete a file or directory and all of its contents- Parameters:
dir
- the directory to delete- Returns:
- true if delete was successful. If false is returned, a partial delete may have occurred.
-
deleteDir
Delete a file or directory and all of its contents- Parameters:
dir
- the dir to delete- Returns:
- true if delete was successful. If false is returned, a partial delete may have occurred.
-
deleteDir
Delete a directory and all of its contents- Parameters:
dir
- the dir to deletemonitor
- the task monitor- Returns:
- true if delete was successful. If false is returned, a partial delete may have occurred.
- Throws:
CancelledException
- if the operation is cancelled
-
copyDir
public static final int copyDir(File originalDir, File copyDir, TaskMonitor monitor) throws IOException, CancelledException This is the same as callingcopyDir(File, File, FileFilter, TaskMonitor)
with aFileFilter
that accepts all files.- Parameters:
originalDir
- the source dircopyDir
- the destination dirmonitor
- the task monitor- Returns:
- the number of filed copied
- Throws:
IOException
- if there is an issue copying the filesCancelledException
- if the operation is cancelled
-
copyDir
public static final int copyDir(File originalDir, File copyDir, FileFilter filter, TaskMonitor monitor) throws IOException, CancelledException Copies the contents oforiginalDir
tocopyDir
. If theoriginalDir
does not exist, then this method will do nothing. IfcopyDir
does not exist, then it will be created as necessary.- Parameters:
originalDir
- The directory from which to extract contentscopyDir
- The directory in which the extracted contents will be placedfilter
- a filter to apply against the directory's contentsmonitor
- the task monitor- Returns:
- the number of filed copied
- Throws:
IOException
- if there was a problem accessing the filesCancelledException
- if the copy is cancelled
-
copyStreamToFile
public static final long copyStreamToFile(InputStream in, File toFile, boolean append, TaskMonitor monitor) throws IOException Copy the in stream to the toFile. The toFile will be overwritten or created.- Parameters:
in
- source input streamtoFile
- destination fileappend
- if true and the file exists, the fromFile contents will be appended to the toFile.monitor
- if specified the progress will be reset and will advance to 100% when the copy is complete.- Returns:
- number of bytes copied from source file to destination file
- Throws:
IOException
- thrown if there was a problem accessing the files
-
copyFileToStream
public static final void copyFileToStream(File fromFile, OutputStream out, TaskMonitor monitor) throws IOException Copy the contents of the specified fromFile to the out stream.- Parameters:
fromFile
- file data sourceout
- destination streammonitor
- if specified the progress will be reset and will advance to 100% when the copy is complete.- Throws:
IOException
- thrown if there was a problem accessing the files
-
copyStreamToStream
public static long copyStreamToStream(InputStream in, OutputStream out, TaskMonitor monitor) throws IOException Copy thein
stream to theout
stream. The output stream will not be closed when the copy operation is finished.- Parameters:
in
- source input streamout
- the destination output streammonitor
- if specified the progress will be reset and will advance to 100% when the copy is complete.- Returns:
- the number of bytes copied from the input stream to the output stream.
- Throws:
IOException
- thrown if there was a problem accessing the files
-
getLines
Returns all of the lines in the file without any newline characters- Parameters:
file
- The file to read in- Returns:
- a list of file lines
- Throws:
IOException
- if an error occurs reading the file
-
getLines
Returns all of the lines in the file without any newline characters.The file is treated as UTF-8 encoded.
- Parameters:
file
- The text file to read in- Returns:
- a list of file lines
- Throws:
IOException
- if an error occurs reading the file
-
getLinesQuietly
Returns all of the lines in the file without any newline characters. This method is the same asgetLines(ResourceFile)
, except that it handles the exception that is thrown by that method.- Parameters:
file
- The file to read in- Returns:
- a list of file lines
-
getLines
Returns all of the lines in the BufferedReader without any newline characters.The file is treated as UTF-8 encoded.
- Parameters:
url
- the input stream from which to read- Returns:
- a list of file lines
- Throws:
IOException
- thrown if there was a problem accessing the files
-
getLines
Returns all of the lines in the givenInputStream
without any newline characters.- Parameters:
is
- the input stream from which to read- Returns:
- a
List
of strings representing the text lines of the file - Throws:
IOException
- if there are any issues reading the file
-
getText
Returns all of the text in the givenInputStream
.EOL characters are normalized to simple '\n's.
- Parameters:
is
- the input stream from which to read- Returns:
- the content as a String
- Throws:
IOException
- if there are any issues reading the file
-
getText
Returns all of the text in the givenFile
.- Parameters:
f
- the file to read- Returns:
- the content as a String
- Throws:
IOException
- if there are any issues reading the file or file is too large.
-
getLines
Returns all of the lines in theBufferedReader
without any newline characters.- Parameters:
in
- BufferedReader to read lines from. The caller is responsible for closing the reader- Returns:
- a
List
of strings representing the text lines of the file - Throws:
IOException
- if there are any issues reading the file
-
writeLinesToFile
Writes the given list of Strings to the file, separating each by a newline character.This will overwrite the contents of the given file!
- Parameters:
file
- the file to which the lines will be writtenlines
- the lines to write- Throws:
IOException
- if there are any issues writing to the file
-
writeStringToFile
Writes the given String to the specifiedFile
.- Parameters:
file
-File
to write to.s
- String to write to the file.- Throws:
IOException
- if there were any issues while writing to the file.
-
isEmpty
Returns true if the given file:- is
null
, or File.isFile()
is true,- and
File.length()
is == 0.
- Parameters:
f
- the file to check- Returns:
- true if the file is not empty
- is
-
isPathContainedWithin
Returns true if the givenpotentialParentFile
is the parent path of the givenotherFile
, or if the two file paths point to the same path.- Parameters:
potentialParentFile
- The file that may be the parentotherFile
- The file that may be the child- Returns:
- boolean true if otherFile's path is within potentialParentFile's path
-
isPathContainedWithin
public static boolean isPathContainedWithin(Collection<ResourceFile> potentialParents, ResourceFile otherFile) Returns true if any of the givenpotentialParents
is the parent path of or has the same path as the givenotherFile
.- Parameters:
potentialParents
- The files that may be the parentotherFile
- The file that may be the child- Returns:
- boolean true if otherFile's path is within any of the potentialParents' paths
-
relativizePath
Returns the portion of the second file that trails the full path of the first file. If the paths are the same or unrelated, then null is returned.For example, given, in this order, two files with these paths
/a/b
and/a/b/c
, this method will return 'c'.- Parameters:
f1
- the parent filef2
- the child file- Returns:
- the portion of the second file that trails the full path of the first file; null as described above
- Throws:
IOException
- if there is an error canonicalizing the path
-
relativizePath
Return the relative path string of one resource file in another. If no path can be constructed or the files are the same, then null is returned. Note: unlikerelativizePath(File, File)
, this function does not resolve symbolic links.For example, given, in this order, two files with these paths
/a/b
and/a/b/c
, this method will return 'c'.- Parameters:
f1
- the parent resource filef2
- the child resource file- Returns:
- the relative path of
f2
inf1
; null if f1 is not a parent of f2
-
exists
-
existsAndIsCaseDependent
Returns true if a file exists on disk and has a case that matches the filesystem. This method is handy for comparing file paths provided externally (like from a user or a config file) to determine if the case of the file path matches the case of the file on the filesystem.- Parameters:
file
- the file to be tested- Returns:
- a result object that reports the status of the file
-
existsAndIsCaseDependent
Returns true if a file exists on disk and has a case that matches the filesystem. This method is handy for comparing file paths provided externally (like from a user or a config file) to determine if the case of the file path matches the case of the file on the filesystem.- Parameters:
file
- the file to be tested- Returns:
- a result object that reports the status of the file
-
resolveFileCaseSensitive
Ensures that the specifiedFile
param points to a file on the filesystem with a filename that has the exact same character case as the filename portion of the specified File.This does not ensure that the path components are case-sensitive.
If the specified File and filesystem file do not match case a NULL is returned, otherwise the original File parameter is returned.
This method is useful on OS's that have filesystems that are case-insensitive and allow using File("A") to open real file "a", and you do not wish to allow this.
If the specified file being queried is a symbolic link to a file with a different name, no case sensitivity checks are done and the original specified File param is returned unchanged.
(Put another way: symlink "FILE1" -> "../path/file2", no case sensitive enforcing can be done, but symlink "FILE1" -> "../path/file1" will be enforced by this method.)
Querying a filepath that does not exist will result in a 'success' and the caller will receive the non-existent File instance back.
-
resolveFileCaseInsensitive
Ensures the specifiedFile
points to a valid existing file, regardless of case match of the file's name.Does not fixup any case-mismatching of the parent directories of the specified file.
If the exact filename already exists, it is returned unchanged, otherwise an all-lowercase version of the filename is probed, and then an all-uppercase version of the filename is probed, returning it if found.
Finally, the entire parent directory of the specified file is listed, and the first file that matches, case-insensitively to the target file, is returned.
If no file is found that matches, the original File instance is returned.
See also
existsAndIsCaseDependent(ResourceFile)
.- Parameters:
f
- File instance- Returns:
- File instance pointing to a case-insensitive match of the File parameter
-
pathToParts
-
getPrettySize
Returns the size of the given file as a human readable String.- Parameters:
file
- the file for which to get size- Returns:
- the pretty string
-
formatLength
Returns a human readable string representing the length of something in bytes.Larger sizes are represented in rounded off kilo and mega bytes.
TODO: why is the method using 1000 vs. 1024 for K?
- Parameters:
length
- the length to format- Returns:
- pretty string - "1.1KB", "5.0MB"
-
setOwnerOnlyPermissions
Sets the given file (or directory) to readable and writable by only the owner.- Parameters:
f
- The file (or directory) to set the permissions of.
-
openNative
Uses theDesktop
API to open the specified file using the user's operating system's native widgets (ie. Windows File Explorer, Mac Finder, etc).If the specified file is a directory, a file explorer will tend to be opened.
If the specified file is a file, the operating system will decide what to do based on the contents or name of the file.
If the
Desktop
API isn't support in the current env (unknown when this will actually happen) an error dialog will be displayed.- Parameters:
file
-File
ref to a directory or file on the local filesystem.- Throws:
IOException
- if the OS doesn't know what to do with the file.
-
forEachFile
A convenience method to list the contents of the given directory path and pass each to the given consumer. If the given path does not represent a directory, nothing will happen.This method handles closing resources by using the try-with-resources construct on
Files.list(Path)
- Parameters:
path
- the directoryconsumer
- the consumer of each child in the given directory- Throws:
IOException
- if there is any problem reading the directory contents
-
forEachFile
A convenience method to list the contents of the given directory path and pass each to the given consumer. If the given path does not represent a directory, nothing will happen.- Parameters:
resourceFile
- the directoryconsumer
- the consumer of each child in the given directory
-
forEachFile
A convenience method to list the contents of the given directory path and pass each to the given consumer. If the given path does not represent a directory, nothing will happen.- Parameters:
resourceFile
- the directoryconsumer
- the consumer of each child in the given directory
-