Class FileUtils


  • public final class FileUtils
    extends java.lang.Object
    • Method Summary

      All Methods Static Methods Concrete Methods 
      Modifier and Type Method Description
      static void cleanOutputDir​(java.io.File path)
      Makes sure path is an empty directory.
      static void copyDirectory​(java.io.File from, java.io.File to)
      Copies a directory from one path to another.
      static void copyDirectoryContentToDirectory​(java.io.File from, java.io.File to)
      Makes a copy of the directory's content, in the specified location, while maintaining the directory structure.
      static void copyDirectoryToDirectory​(java.io.File from, java.io.File to)
      Makes a copy of the given directory in the specified destination directory.
      static void copyFile​(java.io.File from, java.io.File to)
      Copies a regular file from one path to another, preserving file attributes.
      static void copyFile​(java.nio.file.Path from, java.nio.file.Path to)
      Copies a regular file from one path to another.
      static void copyFile​(java.nio.file.Path from, java.nio.file.Path to, java.nio.file.CopyOption... options)
      Copies a regular file from one path to another.
      static void copyFileToDirectory​(java.io.File from, java.io.File to)
      Makes a copy of the given file in the specified directory, preserving the name and file attributes.
      static void createFile​(java.io.File file, java.lang.String content)
      Creates a new text file with the given content.
      static java.nio.file.FileSystem createZipFilesystem​(java.nio.file.Path archive)
      Creates a new FileSystem for a given ZIP file.
      static void delete​(java.io.File file)
      Deletes an existing file or an existing empty directory.
      static void deleteDirectoryContents​(java.io.File directory)
      Recursively deletes a directory content (including the sub directories) but not itself.
      static void deleteIfExists​(java.io.File file)
      Deletes a file or an empty directory if it exists.
      static void deletePath​(java.io.File path)
      Recursively deletes a path.
      static void deleteRecursivelyIfExists​(java.io.File file)
      Deletes a file or a directory if it exists.
      static java.lang.String escapeSystemDependentCharsIfNecessary​(java.lang.String path)
      Escapes all OS dependent chars if necessary.
      static com.google.common.base.Optional<java.io.File> find​(java.io.File base, java.lang.String name)
      Find a file with the specified name in a given directory .
      static java.util.List<java.io.File> find​(java.io.File base, java.util.regex.Pattern pattern)
      Find a list of files in a directory, using a specified path pattern.
      static com.google.common.collect.FluentIterable<java.io.File> getAllFiles​(java.io.File dir)  
      static java.lang.String getDirectoryNameForJar​(java.io.File inputFile)
      Chooses a directory name, based on a JAR file name, considering exploded-aar and classes.jar.
      static java.lang.String getNamesAsCommaSeparatedList​(java.lang.Iterable<java.io.File> files)  
      static boolean isFileInDirectory​(java.io.File fileOrDir, java.io.File baseDir)
      Returns true if a file/directory is located directly or indirectly inside a base directory.
      static boolean isSameFile​(java.io.File file1, java.io.File file2)
      Returns true if the two files refer to the same physical file (or potentially the same physically file when created in the case that the given files do not exist yet).
      static java.io.File join​(java.io.File dir, java.lang.Iterable<java.lang.String> paths)
      Joins a list of path segments to a given File object.
      static java.io.File join​(java.io.File dir, java.lang.String... paths)
      Joins a list of path segments to a given File object.
      static java.lang.String join​(java.lang.Iterable<java.lang.String> paths)
      Joins a set of segment into a string, separating each segments with a host-specific path separator.
      static java.lang.String join​(java.lang.String... paths)
      Joins a set of segment into a string, separating each segments with a host-specific path separator.
      static java.lang.String joinFilePaths​(java.lang.Iterable<java.io.File> files)
      Join multiple file paths as String.
      static java.lang.String loadFileWithUnixLineSeparators​(java.io.File file)
      Loads a text file forcing the line separator to be of Unix style '\n' rather than being Windows style '\r\n'.
      static java.io.File mkdirs​(java.io.File folder)
      Creates a directory, if it doesn't exist.
      static boolean parentDirExists​(java.io.File file)
      Returns true if the parent directory of the given file/directory exists, and false otherwise.
      static java.lang.String relativePath​(java.io.File file, java.io.File dir)
      Computes the relative of a file or directory with respect to a directory.
      static java.lang.String relativePossiblyNonExistingPath​(java.io.File file, java.io.File dir)
      Computes the relative of a file or directory with respect to a directory.
      static void renameTo​(java.io.File file, java.io.File to)  
      static java.lang.String sanitizeFileName​(java.lang.String input)
      Replace all unsafe characters for a file name (OS independent) with an underscore
      static java.lang.String sha1​(java.io.File file)  
      static java.lang.String toExportableSystemDependentPath​(java.io.File file)
      Returns an absolute path that can be open by system APIs for all platforms.
      static java.lang.String toSystemDependentPath​(java.lang.String path)
      Converts a /-based path into a path using the system dependent separator.
      static java.lang.String toSystemIndependentPath​(java.lang.String path)
      Converts a system-dependent path into a /-based path.
      static void writeToFile​(java.io.File file, java.lang.String content)
      Creates a new text file or replaces content of an existing file.
      • Methods inherited from class java.lang.Object

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

      • deletePath

        public static void deletePath​(@NonNull
                                      java.io.File path)
                               throws java.io.IOException
        Recursively deletes a path.
        Parameters:
        path - the path delete, may exist or not
        Throws:
        java.io.IOException - failed to delete the file / directory
      • deleteDirectoryContents

        public static void deleteDirectoryContents​(@NonNull
                                                   java.io.File directory)
                                            throws java.io.IOException
        Recursively deletes a directory content (including the sub directories) but not itself.
        Parameters:
        directory - the directory, that must exist and be a valid directory
        Throws:
        java.io.IOException - failed to delete the file / directory
      • cleanOutputDir

        public static void cleanOutputDir​(@NonNull
                                          java.io.File path)
                                   throws java.io.IOException
        Makes sure path is an empty directory. If path is a directory, its contents are removed recursively, leaving an empty directory. If path is not a directory, it is removed and a directory created with the given path. If path does not exist, a directory is created with the given path.
        Parameters:
        path - the path, that may exist or not and may be a file or directory
        Throws:
        java.io.IOException - failed to delete directory contents, failed to delete path or failed to create a directory at path
      • copyFile

        public static void copyFile​(@NonNull
                                    java.io.File from,
                                    @NonNull
                                    java.io.File to)
                             throws java.io.IOException
        Copies a regular file from one path to another, preserving file attributes. If the destination file exists, it gets overwritten. If the [from] file is read-only on windows, the [to] file will be left read-write so that it can be overwritten the next time this function is called.
        Throws:
        java.io.IOException
      • copyFile

        public static void copyFile​(@NonNull
                                    java.nio.file.Path from,
                                    @NonNull
                                    java.nio.file.Path to)
                             throws java.io.IOException
        Copies a regular file from one path to another. This function uses two standard copy options: - COPY_ATTRIBUTES copies platform-dependent attributes like file timestamp (only used for non-Windows OSes because performance is worse for Windows and better for non-Windows OSes). - REPLACE_EXISTING will try to delete the target file before the copy. If you want other options, there is an overload which lets you set a custom set.

        Lastly, if the [from] file is read-only on windows, the [to] file will be left read-write so that it can be overwritten the next time this function is called.

        Throws:
        java.io.IOException
      • copyFile

        public static void copyFile​(@NonNull
                                    java.nio.file.Path from,
                                    @NonNull
                                    java.nio.file.Path to,
                                    java.nio.file.CopyOption... options)
                             throws java.io.IOException
        Copies a regular file from one path to another. If the [from] file is read-only on windows, the [to] file will be left read-write so that it can be overwritten the next time this function is called.
        Throws:
        java.io.IOException
      • copyDirectory

        public static void copyDirectory​(@NonNull
                                         java.io.File from,
                                         @NonNull
                                         java.io.File to)
                                  throws java.io.IOException
        Copies a directory from one path to another. If the destination directory exists, the file contents are merged and files from the source directory overwrite files in the destination.
        Throws:
        java.io.IOException
      • copyFileToDirectory

        public static void copyFileToDirectory​(@NonNull
                                               java.io.File from,
                                               @NonNull
                                               java.io.File to)
                                        throws java.io.IOException
        Makes a copy of the given file in the specified directory, preserving the name and file attributes.
        Throws:
        java.io.IOException
      • copyDirectoryToDirectory

        public static void copyDirectoryToDirectory​(@NonNull
                                                    java.io.File from,
                                                    @NonNull
                                                    java.io.File to)
                                             throws java.io.IOException
        Makes a copy of the given directory in the specified destination directory.
        Throws:
        java.io.IOException
        See Also:
        copyDirectory(File, File)
      • copyDirectoryContentToDirectory

        public static void copyDirectoryContentToDirectory​(@NonNull
                                                           java.io.File from,
                                                           @NonNull
                                                           java.io.File to)
                                                    throws java.io.IOException
        Makes a copy of the directory's content, in the specified location, while maintaining the directory structure. So the entire directory tree from the source will be copied.
        Parameters:
        from - directory from which the content is copied
        to - destination directory, will be created if does not exist
        Throws:
        java.io.IOException
      • mkdirs

        @NonNull
        public static java.io.File mkdirs​(@NonNull
                                          java.io.File folder)
        Creates a directory, if it doesn't exist.
        Parameters:
        folder - the directory to create, may already exist
        Returns:
        folder
      • delete

        public static void delete​(@NonNull
                                  java.io.File file)
                           throws java.io.IOException
        Deletes an existing file or an existing empty directory.
        Parameters:
        file - the file or directory to delete. The file/directory must exist, if the directory exists, it must be empty.
        Throws:
        java.io.IOException
      • deleteIfExists

        public static void deleteIfExists​(@NonNull
                                          java.io.File file)
                                   throws java.io.IOException
        Deletes a file or an empty directory if it exists.
        Parameters:
        file - the file or directory to delete. The file/directory may not exist; if the directory exists, it must be empty.
        Throws:
        java.io.IOException
      • deleteRecursivelyIfExists

        public static void deleteRecursivelyIfExists​(@NonNull
                                                     java.io.File file)
                                              throws java.io.IOException
        Deletes a file or a directory if it exists. If the directory is not empty, its contents will be deleted recursively.
        Parameters:
        file - the file or directory to delete. The file/directory may not exist; if the directory exists, it may be non-empty.
        Throws:
        java.io.IOException
      • renameTo

        public static void renameTo​(@NonNull
                                    java.io.File file,
                                    @NonNull
                                    java.io.File to)
                             throws java.io.IOException
        Throws:
        java.io.IOException
      • join

        @NonNull
        public static java.io.File join​(@NonNull
                                        java.io.File dir,
                                        @NonNull
                                        java.lang.String... paths)
        Joins a list of path segments to a given File object.
        Parameters:
        dir - the file object.
        paths - the segments.
        Returns:
        a new File object.
      • join

        @NonNull
        public static java.io.File join​(@NonNull
                                        java.io.File dir,
                                        @NonNull
                                        java.lang.Iterable<java.lang.String> paths)
        Joins a list of path segments to a given File object.
        Parameters:
        dir - the file object.
        paths - the segments.
        Returns:
        a new File object.
      • join

        @NonNull
        public static java.lang.String join​(@NonNull
                                            java.lang.String... paths)
        Joins a set of segment into a string, separating each segments with a host-specific path separator.
        Parameters:
        paths - the segments.
        Returns:
        a string with the segments.
      • join

        @NonNull
        public static java.lang.String join​(@NonNull
                                            java.lang.Iterable<java.lang.String> paths)
        Joins a set of segment into a string, separating each segments with a host-specific path separator.
        Parameters:
        paths - the segments.
        Returns:
        a string with the segments.
      • loadFileWithUnixLineSeparators

        @NonNull
        public static java.lang.String loadFileWithUnixLineSeparators​(@NonNull
                                                                      java.io.File file)
                                                               throws java.io.IOException
        Loads a text file forcing the line separator to be of Unix style '\n' rather than being Windows style '\r\n'.
        Throws:
        java.io.IOException
      • relativePath

        @NonNull
        public static java.lang.String relativePath​(@NonNull
                                                    java.io.File file,
                                                    @NonNull
                                                    java.io.File dir)
        Computes the relative of a file or directory with respect to a directory.
        Parameters:
        file - the file or directory, which must exist in the filesystem
        dir - the directory to compute the path relative to
        Returns:
        the relative path from dir to file
      • relativePossiblyNonExistingPath

        @NonNull
        public static java.lang.String relativePossiblyNonExistingPath​(@NonNull
                                                                       java.io.File file,
                                                                       @NonNull
                                                                       java.io.File dir)
        Computes the relative of a file or directory with respect to a directory. For example, if the file's absolute path is /a/b/c and the directory is /a, this method returns b/c.
        Parameters:
        file - the path that may not correspond to any existing path in the filesystem
        dir - the directory to compute the path relative to
        Returns:
        the relative path from dir to file
      • toSystemDependentPath

        @NonNull
        public static java.lang.String toSystemDependentPath​(@NonNull
                                                             java.lang.String path)
        Converts a /-based path into a path using the system dependent separator.
        Parameters:
        path - the system independent path to convert
        Returns:
        the system dependent path
      • escapeSystemDependentCharsIfNecessary

        @NonNull
        public static java.lang.String escapeSystemDependentCharsIfNecessary​(@NonNull
                                                                             java.lang.String path)
        Escapes all OS dependent chars if necessary.
        Parameters:
        path - the file path to escape.
        Returns:
        the escaped file path or itself if it is not necessary.
      • toSystemIndependentPath

        @NonNull
        public static java.lang.String toSystemIndependentPath​(@NonNull
                                                               java.lang.String path)
        Converts a system-dependent path into a /-based path.
        Parameters:
        path - the system dependent path
        Returns:
        the system independent path
      • toExportableSystemDependentPath

        @NonNull
        public static java.lang.String toExportableSystemDependentPath​(@NonNull
                                                                       java.io.File file)
        Returns an absolute path that can be open by system APIs for all platforms.
        Parameters:
        file - The file whose path needs to be converted.
        Returns:
        On non-Windows platforms, the absolute path of the file. On Windows, the absolute path preceded by "\\?\". This ensures that Windows API calls can open the path even if it is more than 260 characters long.
      • sha1

        @NonNull
        public static java.lang.String sha1​(@NonNull
                                            java.io.File file)
                                     throws java.io.IOException
        Throws:
        java.io.IOException
      • getAllFiles

        @NonNull
        public static com.google.common.collect.FluentIterable<java.io.File> getAllFiles​(@NonNull
                                                                                         java.io.File dir)
      • getNamesAsCommaSeparatedList

        @NonNull
        public static java.lang.String getNamesAsCommaSeparatedList​(@NonNull
                                                                    java.lang.Iterable<java.io.File> files)
      • sanitizeFileName

        @NonNull
        public static java.lang.String sanitizeFileName​(java.lang.String input)
        Replace all unsafe characters for a file name (OS independent) with an underscore
        Parameters:
        input - an potentially unsafe file name
        Returns:
        a safe file name
      • getDirectoryNameForJar

        @NonNull
        public static java.lang.String getDirectoryNameForJar​(@NonNull
                                                              java.io.File inputFile)
        Chooses a directory name, based on a JAR file name, considering exploded-aar and classes.jar.
      • createFile

        public static void createFile​(@NonNull
                                      java.io.File file,
                                      @NonNull
                                      java.lang.String content)
                               throws java.io.IOException
        Creates a new text file with the given content. The file should not exist when this method is called.
        Parameters:
        file - the file to write to
        content - the new content of the file
        Throws:
        java.io.IOException
      • writeToFile

        public static void writeToFile​(@NonNull
                                       java.io.File file,
                                       @NonNull
                                       java.lang.String content)
                                throws java.io.IOException
        Creates a new text file or replaces content of an existing file.
        Parameters:
        file - the file to write to
        content - the new content of the file
        Throws:
        java.io.IOException
      • find

        public static java.util.List<java.io.File> find​(@NonNull
                                                        java.io.File base,
                                                        @NonNull
                                                        java.util.regex.Pattern pattern)
        Find a list of files in a directory, using a specified path pattern.
      • find

        public static com.google.common.base.Optional<java.io.File> find​(@NonNull
                                                                         java.io.File base,
                                                                         @NonNull
                                                                         java.lang.String name)
        Find a file with the specified name in a given directory .
      • joinFilePaths

        @NonNull
        public static java.lang.String joinFilePaths​(@NonNull
                                                     java.lang.Iterable<java.io.File> files)
        Join multiple file paths as String.
      • parentDirExists

        public static boolean parentDirExists​(@NonNull
                                              java.io.File file)
        Returns true if the parent directory of the given file/directory exists, and false otherwise. Note that this method resolves the real path of the given file/directory first via File.getCanonicalFile().
      • isFileInDirectory

        public static boolean isFileInDirectory​(@NonNull
                                                java.io.File fileOrDir,
                                                @NonNull
                                                java.io.File baseDir)
        Returns true if a file/directory is located directly or indirectly inside a base directory.

        The given file/directories may or may not exist.

        Note on corner cases:

        • Case sensitivity: Internally, this method uses the Path API, so it is able to take the case sensitivity of the filesystem into account (e.g., file `/a/b` is inside directory `/A` in case-insensitive filesystem).
        • For other corner cases (e.g., hard/symbolic links), please refer to the javadoc of Path.relativize(Path) which this method uses.
      • isSameFile

        public static boolean isSameFile​(@NonNull
                                         java.io.File file1,
                                         @NonNull
                                         java.io.File file2)
        Returns true if the two files refer to the same physical file (or potentially the same physically file when created in the case that the given files do not exist yet).

        This is the correct way to compare physical files, instead of using File.equals(Object) or similar variants.

      • createZipFilesystem

        @NonNull
        public static java.nio.file.FileSystem createZipFilesystem​(@NonNull
                                                                   java.nio.file.Path archive)
                                                            throws java.io.IOException
        Creates a new FileSystem for a given ZIP file.

        Note that NIO filesystems are unique per URI, so the returned FileSystem should be closed as soon as possible.

        Throws:
        java.io.IOException