Class FileUtils


  • public final class FileUtils
    extends Object
    Useful methods for working with file paths.
    Author:
    Johannes Schindelin, Curtis Rueden, Grant Harris
    • Method Detail

      • getPath

        public static String getPath​(File file)
        Gets the absolute path to the given file, with the directory separator standardized to forward slash, like most platforms use.
        Parameters:
        file - The file whose path will be obtained and standardized.
        Returns:
        The file's standardized absolute path.
      • getPath

        public static String getPath​(String path,
                                     String separator)
        Gets a standardized path based on the given one, with the directory separator standardized from the specific separator to forward slash, like most platforms use.
        Parameters:
        path - The path to standardize.
        separator - The directory separator to be standardized.
        Returns:
        The standardized path.
      • getExtension

        public static String getExtension​(File file)
        Extracts the file extension from a file.
        Parameters:
        file - the file object
        Returns:
        the file extension (excluding the dot), or the empty string when the file name does not contain dots
      • getExtension

        public static String getExtension​(String path)
        Extracts the file extension from a file path.
        Parameters:
        path - the path to the file (relative or absolute)
        Returns:
        the file extension (excluding the dot), or the empty string when the file name does not contain dots
      • getModifiedTime

        public static Date getModifiedTime​(File file)
        Gets the Date of the file's last modification.
      • stripFilenameVersion

        public static String stripFilenameVersion​(String filename)
      • getAllVersions

        public static File[] getAllVersions​(File directory,
                                            String filename)
        Lists all versions of a given (possibly versioned) file name.
        Parameters:
        directory - the directory to scan
        filename - the file name to use
        Returns:
        the list of matches
      • urlToFile

        public static File urlToFile​(URL url)
        Converts the given URL to its corresponding File.

        This method is similar to calling new File(url.toURI()) except that it also handles "jar:file:" URLs, returning the path to the JAR file.

        Parameters:
        url - The URL to convert.
        Returns:
        A file path suitable for use with e.g. FileInputStream
        Throws:
        IllegalArgumentException - if the URL does not correspond to a file.
      • urlToFile

        public static File urlToFile​(String url)
        Converts the given URL string to its corresponding File.
        Parameters:
        url - The URL to convert.
        Returns:
        A file path suitable for use with e.g. FileInputStream
        Throws:
        IllegalArgumentException - if the URL does not correspond to a file.
      • shortenPath

        public static String shortenPath​(String path)
        Shortens the path to a maximum of 4 path elements.
        Parameters:
        path - the path to the file (relative or absolute)
        Returns:
        shortened path
      • shortenPath

        public static String shortenPath​(String path,
                                         int threshold)
        Shortens the path based on the given maximum number of path elements. E.g., "C:/1/2/test.txt" returns "C:/1/.../test.txt" if threshold is 1.
        Parameters:
        path - the path to the file (relative or absolute)
        threshold - the number of directories to keep unshortened
        Returns:
        shortened path
      • limitPath

        public static String limitPath​(String path,
                                       int limit)
        Compacts a path into a given number of characters. The result is similar to the Win32 API PathCompactPathExA.
        Parameters:
        path - the path to the file (relative or absolute)
        limit - the number of characters to which the path should be limited
        Returns:
        shortened path
      • createTemporaryDirectory

        public static File createTemporaryDirectory​(String prefix)
                                             throws IOException
        Creates a temporary directory.

        Since there is no atomic operation to do that, we create a temporary file, delete it and create a directory in its place. To avoid race conditions, we use the optimistic approach: if the directory cannot be created, we try to obtain a new temporary file rather than erroring out.

        It is the caller's responsibility to make sure that the directory is deleted; see deleteRecursively(File).

        Parameters:
        prefix - The prefix string to be used in generating the file's name; see File.createTempFile(String, String, File)
        Returns:
        An abstract pathname denoting a newly-created empty directory
        Throws:
        IOException
      • createTemporaryDirectory

        public static File createTemporaryDirectory​(String prefix,
                                                    String suffix)
                                             throws IOException
        Creates a temporary directory.

        Since there is no atomic operation to do that, we create a temporary file, delete it and create a directory in its place. To avoid race conditions, we use the optimistic approach: if the directory cannot be created, we try to obtain a new temporary file rather than erroring out.

        It is the caller's responsibility to make sure that the directory is deleted; see deleteRecursively(File).

        Parameters:
        prefix - The prefix string to be used in generating the file's name; see File.createTempFile(String, String, File)
        suffix - The suffix string to be used in generating the file's name; see File.createTempFile(String, String, File)
        Returns:
        An abstract pathname denoting a newly-created empty directory
        Throws:
        IOException
      • createTemporaryDirectory

        public static File createTemporaryDirectory​(String prefix,
                                                    String suffix,
                                                    File directory)
                                             throws IOException
        Creates a temporary directory.

        Since there is no atomic operation to do that, we create a temporary file, delete it and create a directory in its place. To avoid race conditions, we use the optimistic approach: if the directory cannot be created, we try to obtain a new temporary file rather than erroring out.

        It is the caller's responsibility to make sure that the directory is deleted; see deleteRecursively(File).

        Parameters:
        prefix - The prefix string to be used in generating the file's name; see File.createTempFile(String, String, File)
        suffix - The suffix string to be used in generating the file's name; see File.createTempFile(String, String, File)
        directory - The directory in which the file is to be created, or null if the default temporary-file directory is to be used
        Returns:
        An abstract pathname denoting a newly-created empty directory
        Throws:
        IOException
      • deleteRecursively

        public static boolean deleteRecursively​(File directory)
        Deletes a directory recursively.
        Parameters:
        directory - The directory to delete.
        Returns:
        whether it succeeded (see also File.delete())
      • listContents

        public static Collection<URL> listContents​(URL directory)
        Recursively lists the contents of the referenced directory. Directories are excluded from the result. Supported protocols include file and jar.
        Parameters:
        directory - The directory whose contents should be listed.
        Returns:
        A collection of URLs representing the directory's contents.
        See Also:
        listContents(URL, boolean, boolean)
      • listContents

        public static Collection<URL> listContents​(URL directory,
                                                   boolean recurse,
                                                   boolean filesOnly)
        Lists all contents of the referenced directory. Supported protocols include file and jar.
        Parameters:
        directory - The directory whose contents should be listed.
        recurse - Whether to list contents recursively, as opposed to only the directory's direct contents.
        filesOnly - Whether to exclude directories in the resulting collection of contents.
        Returns:
        A collection of URLs representing the directory's contents.
      • appendContents

        public static Collection<URL> appendContents​(Collection<URL> result,
                                                     URL directory)
        Recursively adds contents from the referenced directory to an existing collection. Directories are excluded from the result. Supported protocols include file and jar.
        Parameters:
        result - The collection to which contents should be added.
        directory - The directory whose contents should be listed.
        Returns:
        A collection of URLs representing the directory's contents.
        See Also:
        appendContents(Collection, URL, boolean, boolean)
      • appendContents

        public static Collection<URL> appendContents​(Collection<URL> result,
                                                     URL directory,
                                                     boolean recurse,
                                                     boolean filesOnly)
        Add contents from the referenced directory to an existing collection. Supported protocols include file and jar.
        Parameters:
        result - The collection to which contents should be added.
        directory - The directory whose contents should be listed.
        recurse - Whether to append contents recursively, as opposed to only the directory's direct contents.
        filesOnly - Whether to exclude directories in the resulting collection of contents.
        Returns:
        A collection of URLs representing the directory's contents.
      • findResources

        public static Map<String,​URL> findResources​(String regex,
                                                          String pathPrefix,
                                                          File baseDirectory)
        Finds URLs of available resources. Both JAR files and files on disk are searched, according to the following mechanism:
        1. Resources at the given pathPrefix are discovered using ClassLoader.getResources(String) with the current thread's context class loader. In particular, this invocation discovers resources in JAR files beneath the given pathPrefix.
        2. The directory named pathPrefix beneath the given baseDirectory is scanned last, so that users can more easily override resources provided inside JAR files by placing a resource of the same name within that directory.

        In both cases, resources are then recursively scanned using listContents(URL), and anything matching the given regex pattern is added to the output map.

        Parameters:
        regex - The regex to use when matching resources, or null to match everything.
        pathPrefix - The path to search for resources.
        baseDirectory - The baseDirectory/pathPrefix directory to scan after the URL resources.
        Returns:
        A map of URLs referencing the matched resources.
        See Also:
        AppUtils.getBaseDirectory(java.lang.String, java.lang.Class<?>, java.lang.String)
      • findResources

        public static Map<String,​URL> findResources​(String regex,
                                                          Iterable<URL> urls)
        Finds URLs of resources known to the system.

        Each of the given URLs is recursively scanned using listContents(URL), and anything matching the given regex pattern is added to the output map.

        Parameters:
        regex - The regex to use when matching resources, or null to match everything.
        urls - Paths to search for resources.
        Returns:
        A map of URLs referencing the matched resources.