Class FileUtilities
- java.lang.Object
-
- utilities.util.FileUtilities
-
public final class FileUtilities extends java.lang.Object
-
-
Field Summary
Fields Modifier and Type Field Description static int
IO_BUFFER_SIZE
-
Method Summary
All Methods Static Methods Concrete Methods Modifier and Type Method Description static void
asyncForEachLine(java.io.BufferedReader reader, java.util.function.Consumer<java.lang.String> consumer)
Processes each text line in a text file, in a separate thread.static void
asyncForEachLine(java.io.InputStream is, java.util.function.Consumer<java.lang.String> consumer)
Processes each text line in a text file, in a separate thread.static java.io.File
checkedMkdir(java.io.File dir)
Ensures the specified leaf directory exists.static java.io.File
checkedMkdirs(java.io.File dir)
Ensures the specified full directory path exists, creating any missing directories as needed.static int
copyDir(java.io.File originalDir, java.io.File copyDir, TaskMonitor monitor)
This is the same as callingcopyDir(File, File, FileFilter, TaskMonitor)
with aFileFilter
that accepts all files.static int
copyDir(java.io.File originalDir, java.io.File copyDir, java.io.FileFilter filter, TaskMonitor monitor)
Copies the contents of originalDir to copyDir.static void
copyFile(ResourceFile fromFile, ResourceFile toFile, TaskMonitor monitor)
Copy the fromFile contents to the toFile.static void
copyFile(ResourceFile fromFile, java.io.File toFile, boolean append, TaskMonitor monitor)
Copy the fromFile contents to the toFile.static long
copyFile(java.io.File fromFile, java.io.File toFile, boolean append, TaskMonitor monitor)
Copy the fromFile contents to the toFile.static void
copyFileToStream(java.io.File fromFile, java.io.OutputStream out, TaskMonitor monitor)
Copy the contents of the specified fromFile to the out stream.static long
copyStreamToFile(java.io.InputStream in, java.io.File toFile, boolean append, TaskMonitor monitor)
Copy the in stream to the toFile.static long
copyStreamToStream(java.io.InputStream in, java.io.OutputStream out, TaskMonitor monitor)
Copy the in stream to the out stream.static boolean
createDir(java.io.File dir)
Ensures the specified leaf directory exists.static java.io.File
createTempDirectory(java.lang.String prefix)
static boolean
deleteDir(java.io.File dir)
Delete a directory and all of its contents.static boolean
deleteDir(java.io.File dir, TaskMonitor monitor)
Delete a directory and all of its contents.static boolean
directoryExistsAndIsNotEmpty(java.io.File directory)
Returns true if the give file is not null, exists, is a directory and contains files.static boolean
directoryIsEmpty(java.io.File directory)
Returns true if the given file is not null, exits, is a directory and has no files.static boolean
exists(java.net.URI uri)
static FileResolutionResult
existsAndIsCaseDependent(ResourceFile file)
Returns true if a file exists on disk and has a case that matches the filesystem.static FileResolutionResult
existsAndIsCaseDependent(java.io.File file)
Returns true if a file exists on disk and has a case that matches the filesystem.static java.lang.String
formatLength(long length)
Returns a human readable string representing the length of something in bytes.static byte[]
getBytes(java.io.InputStream is)
static byte[]
getBytesFromFile(ResourceFile sourceFile)
Return an array of bytes read from the given file.static byte[]
getBytesFromFile(ResourceFile sourceFile, long offset, long length)
Return an array of bytes read from the sourceFile, starting at the given offsetstatic byte[]
getBytesFromFile(java.io.File sourceFile)
Return an array of bytes read from the given file.static byte[]
getBytesFromFile(java.io.File sourceFile, long offset, long length)
Return an array of bytes read from the sourceFile, starting at the given offsetstatic byte[]
getBytesFromStream(java.io.InputStream inputStream, int expectedLength)
Reads the number of bytes indicated by the expectedLength from the input stream and returns them in a byte array.static java.util.List<java.lang.String>
getLines(ResourceFile file)
Returns all of the lines in the file without any newline characters.static java.util.List<java.lang.String>
getLines(java.io.BufferedReader in)
Returns all of the lines in theBufferedReader
without any newline characters.static java.util.List<java.lang.String>
getLines(java.io.File file)
Returns all of the lines in the file without any newline characters.static java.util.List<java.lang.String>
getLines(java.io.InputStream is)
Returns all of the lines in the givenInputStream
without any newline characters.static java.util.List<java.lang.String>
getLines(java.net.URL url)
Returns all of the lines in the BufferedReader without any newline characters.static java.util.List<java.lang.String>
getLinesQuietly(ResourceFile file)
Returns all of the lines in the file without any newline characters.static java.lang.String
getPrettySize(java.io.File file)
Returns the size of the given file as a human readable String.static java.lang.String
getText(java.io.File f)
Returns all of the text in the givenFile
.static java.lang.String
getText(java.io.InputStream is)
Returns all of the text in the givenInputStream
.static boolean
isEmpty(java.io.File f)
Returns true if the given file: is null, orFile.isFile()
is true, andFile.length()
is == 0.static boolean
isPathContainedWithin(java.io.File potentialParentFile, java.io.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
mkdirs(java.io.File dir)
Make all directories in the full directory path specified.static void
openNative(java.io.File file)
Uses theDesktop
API to open the specified file using the user's operating system's native widgets (ie.static java.util.List<java.lang.String>
pathToParts(java.lang.String path)
static java.lang.String
relativizePath(java.io.File f1, java.io.File f2)
Returns the portion of the second file that trails the full path of the first file.static java.io.File
resolveFileCaseInsensitive(java.io.File f)
Ensures the specifiedFile
points to a valid existing file, regardless of case match of the file's name.static java.io.File
resolveFileCaseSensitive(java.io.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
setOwnerOnlyPermissions(java.io.File f)
Sets the given file (or directory) to readable and writable by only the owner.static void
writeBytes(java.io.File file, byte[] bytes)
Writes an array of bytes to a file.static void
writeLinesToFile(java.io.File file, java.util.List<java.lang.String> lines)
Writes the given list of Strings to the file, separating each by a newline character.static void
writeStringToFile(java.io.File file, java.lang.String s)
Writes the given String to the specifiedFile
.
-
-
-
Field Detail
-
IO_BUFFER_SIZE
public static final int IO_BUFFER_SIZE
- See Also:
- Constant Field Values
-
-
Method Detail
-
directoryExistsAndIsNotEmpty
public static boolean directoryExistsAndIsNotEmpty(java.io.File directory)
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(File)
-
directoryIsEmpty
public static boolean directoryIsEmpty(java.io.File directory)
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
public static final byte[] getBytesFromFile(java.io.File sourceFile) throws java.io.IOException
Return an array of bytes read from the given file.- Throws:
java.io.IOException
- if the file could not be accessed
-
getBytesFromFile
public static final byte[] getBytesFromFile(java.io.File sourceFile, long offset, long length) throws java.io.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:
java.io.IOException
- thrown if there was a problem accessing the file or if there weren't at leastlength
bytes read.
-
getBytesFromFile
public static final byte[] getBytesFromFile(ResourceFile sourceFile) throws java.io.IOException
Return an array of bytes read from the given file.- Throws:
java.io.IOException
- if the file could not be accessed
-
writeBytes
public static void writeBytes(java.io.File file, byte[] bytes) throws java.io.FileNotFoundException, java.io.IOException
Writes an array of bytes to a file.- Parameters:
file
- the file to write tobytes
- the array of bytes to write- Throws:
java.io.FileNotFoundException
- thrown if the file path is invalidjava.io.IOException
- thrown if the file can't be written to.
-
getBytesFromFile
public static final byte[] getBytesFromFile(ResourceFile sourceFile, long offset, long length) throws java.io.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:
java.io.IOException
- thrown if there was a problem accessing the file or if there weren't at leastlength
bytes read.
-
getBytes
public static byte[] getBytes(java.io.InputStream is) throws java.io.IOException
- Throws:
java.io.IOException
-
getBytesFromStream
public static byte[] getBytesFromStream(java.io.InputStream inputStream, int expectedLength) throws java.io.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:
java.io.IOException
- if the "expectedLength" number of bytes can't be read from the input stream.
-
copyFile
public static final long copyFile(java.io.File fromFile, java.io.File toFile, boolean append, TaskMonitor monitor) throws java.io.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:
java.io.IOException
- thrown if there was a problem accessing the files
-
copyFile
public static final void copyFile(ResourceFile fromFile, java.io.File toFile, boolean append, TaskMonitor monitor) throws java.io.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:
java.io.IOException
- thrown if there was a problem accessing the files
-
copyFile
public static final void copyFile(ResourceFile fromFile, ResourceFile toFile, TaskMonitor monitor) throws java.io.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:
java.io.IOException
- thrown if there was a problem accessing the files
-
createDir
public static boolean createDir(java.io.File dir)
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
public static boolean mkdirs(java.io.File dir)
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
public static java.io.File checkedMkdir(java.io.File dir) throws java.io.IOException
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
#checkMkdirs(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:
java.io.IOException
- if there was a failure when creating the directory (ie. the parent directory did not exist or other issue).
-
checkedMkdirs
public static java.io.File checkedMkdirs(java.io.File dir) throws java.io.IOException
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:
java.io.IOException
- if there was a failure when creating a directory.
-
deleteDir
public static final boolean deleteDir(java.io.File dir)
Delete a directory and all of its contents.- Parameters:
dir
-- Returns:
- true if delete was successful. If false is returned, a partial delete may have occurred.
-
deleteDir
public static final boolean deleteDir(java.io.File dir, TaskMonitor monitor) throws CancelledException
Delete a directory and all of its contents.- Parameters:
dir
-- Returns:
- true if delete was successful. If false is returned, a partial delete may have occurred.
- Throws:
CancelledException
-
copyDir
public static final int copyDir(java.io.File originalDir, java.io.File copyDir, TaskMonitor monitor) throws java.io.IOException, CancelledException
This is the same as callingcopyDir(File, File, FileFilter, TaskMonitor)
with aFileFilter
that accepts all files.- Throws:
java.io.IOException
CancelledException
-
copyDir
public static final int copyDir(java.io.File originalDir, java.io.File copyDir, java.io.FileFilter filter, TaskMonitor monitor) throws java.io.IOException, CancelledException
Copies the contents of originalDir to copyDir. If the originalDir does not exist, then this method will do nothing. If copyDir 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 placedfileFilte
- a filter to apply against the directory's contents- Throws:
java.io.IOException
CancelledException
-
copyStreamToFile
public static final long copyStreamToFile(java.io.InputStream in, java.io.File toFile, boolean append, TaskMonitor monitor) throws java.io.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:
java.io.IOException
- thrown if there was a problem accessing the files
-
copyFileToStream
public static final void copyFileToStream(java.io.File fromFile, java.io.OutputStream out, TaskMonitor monitor) throws java.io.IOException
Copy the contents of the specified fromFile to the out stream.- Parameters:
fromFile
- file data sourcetoFile
- destination streammonitor
- if specified the progress will be reset and will advance to 100% when the copy is complete.- Throws:
java.io.IOException
- thrown if there was a problem accessing the files
-
copyStreamToStream
public static long copyStreamToStream(java.io.InputStream in, java.io.OutputStream out, TaskMonitor monitor) throws java.io.IOException
Copy the in stream to the out 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:
java.io.IOException
- thrown if there was a problem accessing the files
-
getLines
public static java.util.List<java.lang.String> getLines(java.io.File file) throws java.io.IOException
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:
java.io.IOException
-
getLines
public static java.util.List<java.lang.String> getLines(ResourceFile file) throws java.io.IOException
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:
java.io.IOException
-
getLinesQuietly
public static java.util.List<java.lang.String> getLinesQuietly(ResourceFile file)
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
public static java.util.List<java.lang.String> getLines(java.net.URL url) throws java.io.IOException
Returns all of the lines in the BufferedReader without any newline characters.The file is treated as UTF-8 encoded.
- Parameters:
is
- the input stream from which to read- Returns:
- a list of file lines
- Throws:
java.io.IOException
-
getLines
public static java.util.List<java.lang.String> getLines(java.io.InputStream is) throws java.io.IOException
Returns all of the lines in the givenInputStream
without any newline characters.The input stream is closed as a side-effect.
- Parameters:
is
- the input stream from which to read, as a side effect, it is closed- Returns:
- a
List
of strings representing the text lines of the file - Throws:
java.io.IOException
- if there are any issues reading the file
-
getText
public static java.lang.String getText(java.io.InputStream is) throws java.io.IOException
Returns all of the text in the givenInputStream
.EOL characters are normalized to simple '\n's.
The input stream is closed as a side-effect.
- Parameters:
is
- the input stream from which to read, as a side effect, it is closed- Returns:
- the content as a String
- Throws:
java.io.IOException
- if there are any issues reading the file
-
getText
public static java.lang.String getText(java.io.File f) throws java.io.IOException
Returns all of the text in the givenFile
.- Parameters:
f
- the file to read- Returns:
- the content as a String
- Throws:
java.io.IOException
- if there are any issues reading the file or file is too large.
-
getLines
public static java.util.List<java.lang.String> getLines(java.io.BufferedReader in) throws java.io.IOException
Returns all of the lines in theBufferedReader
without any newline characters.The BufferedReader is closed before returning.
- Parameters:
in
- BufferedReader to read lines from, as a side effect, it is closed- Returns:
- a
List
of strings representing the text lines of the file - Throws:
java.io.IOException
- if there are any issues reading the file
-
writeLinesToFile
public static void writeLinesToFile(java.io.File file, java.util.List<java.lang.String> lines) throws java.io.IOException
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:
java.io.IOException
- if there are any issues writing to the file
-
writeStringToFile
public static void writeStringToFile(java.io.File file, java.lang.String s) throws java.io.IOException
Writes the given String to the specifiedFile
.- Parameters:
file
-File
to write to.s
- String to write to the file.- Throws:
java.io.IOException
- if there were any issues while writing to the file.
-
isEmpty
public static boolean isEmpty(java.io.File f)
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
-
isPathContainedWithin
public static boolean isPathContainedWithin(java.io.File potentialParentFile, java.io.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.- 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.
-
relativizePath
public static java.lang.String relativizePath(java.io.File f1, java.io.File f2) throws java.io.IOException
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.
- Throws:
java.io.IOException
-
exists
public static boolean exists(java.net.URI uri)
-
existsAndIsCaseDependent
public static FileResolutionResult existsAndIsCaseDependent(java.io.File file)
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
public static FileResolutionResult existsAndIsCaseDependent(ResourceFile file)
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
public static java.io.File resolveFileCaseSensitive(java.io.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.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.
- Parameters:
caseSensitiveFile
-File
to enforce case-sensitive-ness of the name portion- Returns:
- the same
File
instance if it points to a file on the filesystem with the same case, or a NULL if the case does not match.
-
resolveFileCaseInsensitive
public static java.io.File resolveFileCaseInsensitive(java.io.File f)
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
public static java.util.List<java.lang.String> pathToParts(java.lang.String path)
-
getPrettySize
public static java.lang.String getPrettySize(java.io.File file)
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
public static java.lang.String formatLength(long length)
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
-- Returns:
- pretty string - "1.1KB", "5.0MB"
-
createTempDirectory
public static java.io.File createTempDirectory(java.lang.String prefix)
-
setOwnerOnlyPermissions
public static void setOwnerOnlyPermissions(java.io.File f)
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
public static void openNative(java.io.File file) throws java.io.IOException
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:
java.io.IOException
- if the OS doesn't know what to do with the file.
-
asyncForEachLine
public static void asyncForEachLine(java.io.InputStream is, java.util.function.Consumer<java.lang.String> consumer)
Processes each text line in a text file, in a separate thread.Thread exits when EOF is reached.
- Parameters:
is
-InputStream
to readconsumer
- code that will process each text of the text file.
-
asyncForEachLine
public static void asyncForEachLine(java.io.BufferedReader reader, java.util.function.Consumer<java.lang.String> consumer)
Processes each text line in a text file, in a separate thread.Thread exits when EOF is reached.
- Parameters:
reader
-BufferedReader
to readconsumer
- code that will process each text of the text file.
-
-