Class FileUtilities

java.lang.Object
utilities.util.FileUtilities

public final class FileUtilities extends Object
  • Field Details

  • Method Details

    • directoryExistsAndIsNotEmpty

      public static boolean directoryExistsAndIsNotEmpty(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

      public static boolean directoryIsEmpty(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(File sourceFile) throws IOException
      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 from
      offset - offset into the file to begin reading
      length - 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 least length bytes read.
    • getBytesFromFile

      public static final byte[] getBytesFromFile(ResourceFile sourceFile) throws IOException
      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

      public static void writeBytes(File file, byte[] bytes) throws FileNotFoundException, IOException
      Writes an array of bytes to a file.
      Parameters:
      file - the file to write to
      bytes - the array of bytes to write
      Throws:
      FileNotFoundException - thrown if the file path is invalid
      IOException - 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 from
      offset - offset into the file to begin reading
      length - 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 least length bytes read.
    • getBytesFromStream

      public static byte[] getBytesFromStream(InputStream is) throws IOException
      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 stream
      expectedLength - 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 file
      toFile - destination file
      append - 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 file
      toFile - destination file
      append - 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 file
      toFile - destination file
      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
    • createDir

      public static boolean createDir(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(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 File checkedMkdir(File dir) throws 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 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

      public static File checkedMkdirs(File dir) throws 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:
      IOException - if there was a failure when creating a directory.
    • deleteDir

      public static boolean deleteDir(Path dir)
      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

      public static final boolean deleteDir(File dir)
      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

      public static final boolean deleteDir(File dir, TaskMonitor monitor) throws CancelledException
      Delete a directory and all of its contents
      Parameters:
      dir - the dir to delete
      monitor - 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 calling copyDir(File, File, FileFilter, TaskMonitor) with a FileFilter that accepts all files.
      Parameters:
      originalDir - the source dir
      copyDir - the destination dir
      monitor - the task monitor
      Returns:
      the number of filed copied
      Throws:
      IOException - if there is an issue copying the files
      CancelledException - 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 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 contents
      copyDir - The directory in which the extracted contents will be placed
      filter - a filter to apply against the directory's contents
      monitor - the task monitor
      Returns:
      the number of filed copied
      Throws:
      IOException - if there was a problem accessing the files
      CancelledException - 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 stream
      toFile - destination file
      append - 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 source
      out - destination stream
      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
    • copyStreamToStream

      public static long copyStreamToStream(InputStream in, OutputStream out, TaskMonitor monitor) throws 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 stream
      out - the destination output stream
      monitor - 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

      public static List<String> getLines(File file) throws 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:
      IOException - if an error occurs reading the file
    • getLines

      public static List<String> getLines(ResourceFile file) throws 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:
      IOException - if an error occurs reading the file
    • getLinesQuietly

      public static List<String> getLinesQuietly(ResourceFile file)
      Returns all of the lines in the file without any newline characters. This method is the same as getLines(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 List<String> getLines(URL url) throws IOException
      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

      public static List<String> getLines(InputStream is) throws IOException
      Returns all of the lines in the given InputStream 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

      public static String getText(InputStream is) throws IOException
      Returns all of the text in the given InputStream.

      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

      public static String getText(File f) throws IOException
      Returns all of the text in the given File.

      See getText(InputStream)

      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

      public static List<String> getLines(BufferedReader in) throws IOException
      Returns all of the lines in the BufferedReader 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

      public static void writeLinesToFile(File file, List<String> lines) throws 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 written
      lines - the lines to write
      Throws:
      IOException - if there are any issues writing to the file
    • writeStringToFile

      public static void writeStringToFile(File file, String s) throws IOException
      Writes the given String to the specified File.
      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

      public static boolean isEmpty(File f)
      Returns true if the given file:
      1. is null, or
      2. File.isFile() is true,
      3. and File.length() is == 0.
      Parameters:
      f - the file to check
      Returns:
      true if the file is not empty
    • isPathContainedWithin

      public static boolean isPathContainedWithin(File potentialParentFile, File otherFile)
      Returns true if the given potentialParentFile is the parent path of the given otherFile, or if the two file paths point to the same path.
      Parameters:
      potentialParentFile - The file that may be the parent
      otherFile - 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 given potentialParents is the parent path of or has the same path as the given otherFile.
      Parameters:
      potentialParents - The files that may be the parent
      otherFile - The file that may be the child
      Returns:
      boolean true if otherFile's path is within any of the potentialParents' paths
    • relativizePath

      public static String relativizePath(File f1, File f2) throws 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 file
      f2 - 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

      public static String relativizePath(ResourceFile f1, ResourceFile f2)
      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: unlike relativizePath(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 file
      f2 - the child resource file
      Returns:
      the relative path of f2 in f1; null if f1 is not a parent of f2
    • exists

      public static boolean exists(URI uri)
    • existsAndIsCaseDependent

      public static FileResolutionResult existsAndIsCaseDependent(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 File resolveFileCaseSensitive(File caseSensitiveFile)
      Ensures that the specified File 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 File resolveFileCaseInsensitive(File f)
      Ensures the specified File 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 List<String> pathToParts(String path)
    • getPrettySize

      public static String getPrettySize(File file)
      Returns the size of the given file as a human readable String.

      See formatLength(long)

      Parameters:
      file - the file for which to get size
      Returns:
      the pretty string
    • formatLength

      public static 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 - the length to format
      Returns:
      pretty string - "1.1KB", "5.0MB"
    • setOwnerOnlyPermissions

      public static void setOwnerOnlyPermissions(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(File file) throws IOException
      Uses the Desktop 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

      public static void forEachFile(Path path, Consumer<Path> consumer) throws IOException
      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 directory
      consumer - the consumer of each child in the given directory
      Throws:
      IOException - if there is any problem reading the directory contents
    • forEachFile

      public 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. If the given path does not represent a directory, nothing will happen.
      Parameters:
      resourceFile - the directory
      consumer - the consumer of each child in the given directory
    • forEachFile

      public 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. If the given path does not represent a directory, nothing will happen.
      Parameters:
      resourceFile - the directory
      consumer - the consumer of each child in the given directory