Class MoreFiles


  • public final class MoreFiles
    extends java.lang.Object
    Static utilities for use with Path instances, intended to complement Files.

    Many methods provided by Guava's Files class for File instances are now available via the JDK's Files class for Path - check the JDK's class if a sibling method from Files appears to be missing from this class.

    Since:
    21.0
    • Constructor Summary

      Constructors 
      Modifier Constructor Description
      private MoreFiles()  
    • Method Summary

      All Methods Static Methods Concrete Methods 
      Modifier and Type Method Description
      private static java.util.Collection<java.io.IOException> addException​(java.util.Collection<java.io.IOException> exceptions, java.io.IOException e)
      Adds the given exception to the given collection, creating the collection if it's null.
      static ByteSink asByteSink​(java.nio.file.Path path, java.nio.file.OpenOption... options)
      Returns a view of the given path as a ByteSink.
      static ByteSource asByteSource​(java.nio.file.Path path, java.nio.file.OpenOption... options)
      Returns a view of the given path as a ByteSource.
      static CharSink asCharSink​(java.nio.file.Path path, java.nio.charset.Charset charset, java.nio.file.OpenOption... options)
      Returns a view of the given path as a CharSink using the given charset.
      static CharSource asCharSource​(java.nio.file.Path path, java.nio.charset.Charset charset, java.nio.file.OpenOption... options)
      Returns a view of the given path as a CharSource using the given charset.
      private static void checkAllowsInsecure​(java.nio.file.Path path, RecursiveDeleteOption[] options)
      Checks that the given options allow an insecure delete, throwing an exception if not.
      private static java.util.Collection<java.io.IOException> concat​(java.util.Collection<java.io.IOException> exceptions, java.util.Collection<java.io.IOException> other)
      Concatenates the contents of the two given collections of exceptions.
      static void createParentDirectories​(java.nio.file.Path path, java.nio.file.attribute.FileAttribute<?>... attrs)
      Creates any necessary but nonexistent parent directories of the specified path.
      static void deleteDirectoryContents​(java.nio.file.Path path, RecursiveDeleteOption... options)
      Deletes all files within the directory at the given path recursively.
      private static java.util.Collection<java.io.IOException> deleteDirectoryContentsInsecure​(java.nio.file.DirectoryStream<java.nio.file.Path> dir)
      Simple, insecure method for deleting the contents of a directory for file systems that don't support SecureDirectoryStream.
      private static java.util.Collection<java.io.IOException> deleteDirectoryContentsSecure​(java.nio.file.SecureDirectoryStream<java.nio.file.Path> dir)
      Secure method for deleting the contents of a directory using SecureDirectoryStream.
      static void deleteRecursively​(java.nio.file.Path path, RecursiveDeleteOption... options)
      Deletes the file or directory at the given path recursively.
      private static java.util.Collection<java.io.IOException> deleteRecursivelyInsecure​(java.nio.file.Path path)
      Insecure recursive delete for file systems that don't support SecureDirectoryStream.
      private static java.util.Collection<java.io.IOException> deleteRecursivelySecure​(java.nio.file.SecureDirectoryStream<java.nio.file.Path> dir, java.nio.file.Path path)
      Secure recursive delete using SecureDirectoryStream.
      static boolean equal​(java.nio.file.Path path1, java.nio.file.Path path2)
      Returns true if the files located by the given paths exist, are not directories, and contain the same bytes.
      static Traverser<java.nio.file.Path> fileTraverser()
      Returns a Traverser instance for the file and directory tree.
      private static java.lang.Iterable<java.nio.file.Path> fileTreeChildren​(java.nio.file.Path dir)  
      static java.lang.String getFileExtension​(java.nio.file.Path path)
      Returns the file extension for the file at the given path, or the empty string if the file has no extension.
      static java.lang.String getNameWithoutExtension​(java.nio.file.Path path)
      Returns the file name without its file extension or path.
      private static java.nio.file.Path getParentPath​(java.nio.file.Path path)
      Returns a path to the parent directory of the given path.
      static Predicate<java.nio.file.Path> isDirectory​(java.nio.file.LinkOption... options)
      Returns a predicate that returns the result of Files.isDirectory(Path, LinkOption...) on input paths with the given link options.
      private static boolean isDirectory​(java.nio.file.SecureDirectoryStream<java.nio.file.Path> dir, java.nio.file.Path name, java.nio.file.LinkOption... options)
      Returns whether or not the file with the given name in the given dir is a directory.
      static Predicate<java.nio.file.Path> isRegularFile​(java.nio.file.LinkOption... options)
      Returns a predicate that returns the result of Files.isRegularFile(Path, LinkOption...) on input paths with the given link options.
      static ImmutableList<java.nio.file.Path> listFiles​(java.nio.file.Path dir)
      Returns an immutable list of paths to the files contained in the given directory.
      private static java.nio.file.NoSuchFileException pathNotFound​(java.nio.file.Path path, java.util.Collection<java.io.IOException> exceptions)  
      private static void throwDeleteFailed​(java.nio.file.Path path, java.util.Collection<java.io.IOException> exceptions)
      Throws an exception indicating that one or more files couldn't be deleted when deleting path or its contents.
      static void touch​(java.nio.file.Path path)
      Like the unix command of the same name, creates an empty file or updates the last modified timestamp of the existing file at the given path to the current system time.
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    • Constructor Detail

      • MoreFiles

        private MoreFiles()
    • Method Detail

      • asByteSource

        public static ByteSource asByteSource​(java.nio.file.Path path,
                                              java.nio.file.OpenOption... options)
        Returns a view of the given path as a ByteSource.

        Any open options provided are used when opening streams to the file and may affect the behavior of the returned source and the streams it provides. See StandardOpenOption for the standard options that may be provided. Providing no options is equivalent to providing the READ option.

      • asByteSink

        public static ByteSink asByteSink​(java.nio.file.Path path,
                                          java.nio.file.OpenOption... options)
        Returns a view of the given path as a ByteSink.

        Any open options provided are used when opening streams to the file and may affect the behavior of the returned sink and the streams it provides. See StandardOpenOption for the standard options that may be provided. Providing no options is equivalent to providing the CREATE, TRUNCATE_EXISTING and WRITE options.

      • asCharSource

        public static CharSource asCharSource​(java.nio.file.Path path,
                                              java.nio.charset.Charset charset,
                                              java.nio.file.OpenOption... options)
        Returns a view of the given path as a CharSource using the given charset.

        Any open options provided are used when opening streams to the file and may affect the behavior of the returned source and the streams it provides. See StandardOpenOption for the standard options that may be provided. Providing no options is equivalent to providing the READ option.

      • asCharSink

        public static CharSink asCharSink​(java.nio.file.Path path,
                                          java.nio.charset.Charset charset,
                                          java.nio.file.OpenOption... options)
        Returns a view of the given path as a CharSink using the given charset.

        Any open options provided are used when opening streams to the file and may affect the behavior of the returned sink and the streams it provides. See StandardOpenOption for the standard options that may be provided. Providing no options is equivalent to providing the CREATE, TRUNCATE_EXISTING and WRITE options.

      • listFiles

        public static ImmutableList<java.nio.file.Path> listFiles​(java.nio.file.Path dir)
                                                           throws java.io.IOException
        Returns an immutable list of paths to the files contained in the given directory.
        Throws:
        java.nio.file.NoSuchFileException - if the file does not exist (optional specific exception)
        java.nio.file.NotDirectoryException - if the file could not be opened because it is not a directory (optional specific exception)
        java.io.IOException - if an I/O error occurs
      • fileTraverser

        public static Traverser<java.nio.file.Path> fileTraverser()
        Returns a Traverser instance for the file and directory tree. The returned traverser starts from a Path and will return all files and directories it encounters.

        The returned traverser attempts to avoid following symbolic links to directories. However, the traverser cannot guarantee that it will not follow symbolic links to directories as it is possible for a directory to be replaced with a symbolic link between checking if the file is a directory and actually reading the contents of that directory.

        If the Path passed to one of the traversal methods does not exist or is not a directory, no exception will be thrown and the returned Iterable will contain a single element: that path.

        DirectoryIteratorException may be thrown when iterating Iterable instances created by this traverser if an IOException is thrown by a call to listFiles(Path).

        Example: MoreFiles.fileTraverser().depthFirstPreOrder(Paths.get("/")) may return the following paths: ["/", "/etc", "/etc/config.txt", "/etc/fonts", "/home", "/home/alice", ...]

        Since:
        23.5
      • fileTreeChildren

        private static java.lang.Iterable<java.nio.file.Path> fileTreeChildren​(java.nio.file.Path dir)
      • isDirectory

        public static Predicate<java.nio.file.Path> isDirectory​(java.nio.file.LinkOption... options)
        Returns a predicate that returns the result of Files.isDirectory(Path, LinkOption...) on input paths with the given link options.
      • isDirectory

        private static boolean isDirectory​(java.nio.file.SecureDirectoryStream<java.nio.file.Path> dir,
                                           java.nio.file.Path name,
                                           java.nio.file.LinkOption... options)
                                    throws java.io.IOException
        Returns whether or not the file with the given name in the given dir is a directory.
        Throws:
        java.io.IOException
      • isRegularFile

        public static Predicate<java.nio.file.Path> isRegularFile​(java.nio.file.LinkOption... options)
        Returns a predicate that returns the result of Files.isRegularFile(Path, LinkOption...) on input paths with the given link options.
      • equal

        public static boolean equal​(java.nio.file.Path path1,
                                    java.nio.file.Path path2)
                             throws java.io.IOException
        Returns true if the files located by the given paths exist, are not directories, and contain the same bytes.
        Throws:
        java.io.IOException - if an I/O error occurs
        Since:
        22.0
      • touch

        public static void touch​(java.nio.file.Path path)
                          throws java.io.IOException
        Like the unix command of the same name, creates an empty file or updates the last modified timestamp of the existing file at the given path to the current system time.
        Throws:
        java.io.IOException
      • createParentDirectories

        public static void createParentDirectories​(java.nio.file.Path path,
                                                   java.nio.file.attribute.FileAttribute<?>... attrs)
                                            throws java.io.IOException
        Creates any necessary but nonexistent parent directories of the specified path. Note that if this operation fails, it may have succeeded in creating some (but not all) of the necessary parent directories. The parent directory is created with the given attrs.
        Throws:
        java.io.IOException - if an I/O error occurs, or if any necessary but nonexistent parent directories of the specified file could not be created.
      • getFileExtension

        public static java.lang.String getFileExtension​(java.nio.file.Path path)
        Returns the file extension for the file at the given path, or the empty string if the file has no extension. The result does not include the '.'.

        Note: This method simply returns everything after the last '.' in the file's name as determined by Path.getFileName(). It does not account for any filesystem-specific behavior that the Path API does not already account for. For example, on NTFS it will report "txt" as the extension for the filename "foo.exe:.txt" even though NTFS will drop the ":.txt" part of the name when the file is actually created on the filesystem due to NTFS's Alternate Data Streams.

      • getNameWithoutExtension

        public static java.lang.String getNameWithoutExtension​(java.nio.file.Path path)
        Returns the file name without its file extension or path. This is similar to the basename unix command. The result does not include the '.'.
      • deleteRecursively

        public static void deleteRecursively​(java.nio.file.Path path,
                                             RecursiveDeleteOption... options)
                                      throws java.io.IOException
        Deletes the file or directory at the given path recursively. Deletes symbolic links, not their targets (subject to the caveat below).

        If an I/O exception occurs attempting to read, open or delete any file under the given directory, this method skips that file and continues. All such exceptions are collected and, after attempting to delete all files, an IOException is thrown containing those exceptions as suppressed exceptions.

        Warning: Security of recursive deletes

        On a file system that supports symbolic links and does not support SecureDirectoryStream, it is possible for a recursive delete to delete files and directories that are outside the directory being deleted. This can happen if, after checking that a file is a directory (and not a symbolic link), that directory is replaced by a symbolic link to an outside directory before the call that opens the directory to read its entries.

        By default, this method throws InsecureRecursiveDeleteException if it can't guarantee the security of recursive deletes. If you wish to allow the recursive deletes anyway, pass RecursiveDeleteOption.ALLOW_INSECURE to this method to override that behavior.

        Throws:
        java.nio.file.NoSuchFileException - if path does not exist (optional specific exception)
        InsecureRecursiveDeleteException - if the security of recursive deletes can't be guaranteed for the file system and RecursiveDeleteOption.ALLOW_INSECURE was not specified
        java.io.IOException - if path or any file in the subtree rooted at it can't be deleted for any reason
      • deleteDirectoryContents

        public static void deleteDirectoryContents​(java.nio.file.Path path,
                                                   RecursiveDeleteOption... options)
                                            throws java.io.IOException
        Deletes all files within the directory at the given path recursively. Does not delete the directory itself. Deletes symbolic links, not their targets (subject to the caveat below). If path itself is a symbolic link to a directory, that link is followed and the contents of the directory it targets are deleted.

        If an I/O exception occurs attempting to read, open or delete any file under the given directory, this method skips that file and continues. All such exceptions are collected and, after attempting to delete all files, an IOException is thrown containing those exceptions as suppressed exceptions.

        Warning: Security of recursive deletes

        On a file system that supports symbolic links and does not support SecureDirectoryStream, it is possible for a recursive delete to delete files and directories that are outside the directory being deleted. This can happen if, after checking that a file is a directory (and not a symbolic link), that directory is replaced by a symbolic link to an outside directory before the call that opens the directory to read its entries.

        By default, this method throws InsecureRecursiveDeleteException if it can't guarantee the security of recursive deletes. If you wish to allow the recursive deletes anyway, pass RecursiveDeleteOption.ALLOW_INSECURE to this method to override that behavior.

        Throws:
        java.nio.file.NoSuchFileException - if path does not exist (optional specific exception)
        java.nio.file.NotDirectoryException - if the file at path is not a directory (optional specific exception)
        InsecureRecursiveDeleteException - if the security of recursive deletes can't be guaranteed for the file system and RecursiveDeleteOption.ALLOW_INSECURE was not specified
        java.io.IOException - if one or more files can't be deleted for any reason
      • deleteRecursivelySecure

        @CheckForNull
        private static java.util.Collection<java.io.IOException> deleteRecursivelySecure​(java.nio.file.SecureDirectoryStream<java.nio.file.Path> dir,
                                                                                         java.nio.file.Path path)
        Secure recursive delete using SecureDirectoryStream. Returns a collection of exceptions that occurred or null if no exceptions were thrown.
      • deleteDirectoryContentsSecure

        @CheckForNull
        private static java.util.Collection<java.io.IOException> deleteDirectoryContentsSecure​(java.nio.file.SecureDirectoryStream<java.nio.file.Path> dir)
        Secure method for deleting the contents of a directory using SecureDirectoryStream. Returns a collection of exceptions that occurred or null if no exceptions were thrown.
      • deleteRecursivelyInsecure

        @CheckForNull
        private static java.util.Collection<java.io.IOException> deleteRecursivelyInsecure​(java.nio.file.Path path)
        Insecure recursive delete for file systems that don't support SecureDirectoryStream. Returns a collection of exceptions that occurred or null if no exceptions were thrown.
      • deleteDirectoryContentsInsecure

        @CheckForNull
        private static java.util.Collection<java.io.IOException> deleteDirectoryContentsInsecure​(java.nio.file.DirectoryStream<java.nio.file.Path> dir)
        Simple, insecure method for deleting the contents of a directory for file systems that don't support SecureDirectoryStream. Returns a collection of exceptions that occurred or null if no exceptions were thrown.
      • getParentPath

        @CheckForNull
        private static java.nio.file.Path getParentPath​(java.nio.file.Path path)
        Returns a path to the parent directory of the given path. If the path actually has a parent path, this is simple. Otherwise, we need to do some trickier things. Returns null if the path is a root or is the empty path.
      • addException

        private static java.util.Collection<java.io.IOException> addException​(@CheckForNull
                                                                              java.util.Collection<java.io.IOException> exceptions,
                                                                              java.io.IOException e)
        Adds the given exception to the given collection, creating the collection if it's null. Returns the collection.
      • concat

        @CheckForNull
        private static java.util.Collection<java.io.IOException> concat​(@CheckForNull
                                                                        java.util.Collection<java.io.IOException> exceptions,
                                                                        @CheckForNull
                                                                        java.util.Collection<java.io.IOException> other)
        Concatenates the contents of the two given collections of exceptions. If either collection is null, the other collection is returned. Otherwise, the elements of other are added to exceptions and exceptions is returned.
      • throwDeleteFailed

        private static void throwDeleteFailed​(java.nio.file.Path path,
                                              java.util.Collection<java.io.IOException> exceptions)
                                       throws java.nio.file.FileSystemException
        Throws an exception indicating that one or more files couldn't be deleted when deleting path or its contents.

        If there is only one exception in the collection, and it is a NoSuchFileException thrown because path itself didn't exist, then throws that exception. Otherwise, the thrown exception contains all the exceptions in the given collection as suppressed exceptions.

        Throws:
        java.nio.file.FileSystemException
      • pathNotFound

        @CheckForNull
        private static java.nio.file.NoSuchFileException pathNotFound​(java.nio.file.Path path,
                                                                      java.util.Collection<java.io.IOException> exceptions)