Class FileTools


  • public final class FileTools
    extends Object
    Utility class containing file-related helper methods, mostly concerning file names and paths.
    • Field Detail

      • ILLEGAL_CHARS

        public static final String ILLEGAL_CHARS
        A string containing characters illegal for file names. These have been determined on Windows XP and NTFS and should represent a superset of illegal characters across all or at least most OSes.
      • ILLEGAL_CHARS_WEB

        public static final String ILLEGAL_CHARS_WEB
        The characters which are not valid for a web server, which is ILLEGAL_CHARS and some more characters.
      • ILLEGAL_CHARS_WEB_START_END

        public static final String ILLEGAL_CHARS_WEB_START_END
        The characters which are not valid as first or last character for a file on a web server.
    • Method Detail

      • getExtension

        public static String getExtension​(File file)
        Returns the filename's extension, i.e. the characters after the last dot. This method does not differentiate between "no extension" (the filename contains no dot) and "empty extension" (the dot is the final character in the filename). In both cases the empty string is returned.
        Parameters:
        file - the file for which to get the extension
        Returns:
        the filename extension or the empty string
      • getExtension

        public static String getExtension​(String filename)
        Returns the file's extension, i.e. the characters after the last dot. This method does not differentiate between "no extension" (the filename contains no dot) and "empty extension" (the dot is the final character in the filename). In both cases the empty string is returned.
        Parameters:
        filename - the filename for which to get the extension
        Returns:
        the filename extension or the empty string
      • hasExtension

        public static boolean hasExtension​(File file,
                                           String extension)
        Tests whether the given file has the given extension. The comparison is done in a case-insensitive way.
        Parameters:
        file - the file whose extension should be tested
        extension - the extension to test for
        Returns:
        whether the given file has the given extension
      • getWithoutExtension

        public static File getWithoutExtension​(File file)
        Returns the given file without the filename extension.
        Parameters:
        file - the file from which to remove the extension
        Returns:
        the given file without the filename extension
      • getWithoutExtension

        public static String getWithoutExtension​(String path)
        Returns the given file path without the filename extension.
        Parameters:
        path - the file path from which to remove the extension
        Returns:
        the given file path without the filename extension
      • relativise

        public static Path relativise​(String base,
                                      String target)
        Gets the path of target relative to the designated base. base and target must either both be absolute or both be relative.
        Parameters:
        base - The path as base for the relative path.
        target - The file or directory for which to determine a relative path relative to base.
        Returns:
        A relative path that resolves against base to target. This will be null if no relative path is possible.
      • relativise

        public static Path relativise​(Path base,
                                      Path target)
        Gets the path of target relative to the designated base. base and target must either both be absolute or both be relative.
        Parameters:
        base - The path as base for the relative path.
        target - The file or directory for which to determine a relative path relative to base.
        Returns:
        A relative path that resolves against base to target. This will be null if no relative path is possible.
      • sanitise

        public static String sanitise​(String filename,
                                      String replacement)
        Sanitises the name of a file (i.e. without any path) by replacing every illegal character with the given string.
        Parameters:
        filename - the filename to sanitise
        replacement - the replacement for illegal characters
        Returns:
        the sanitised filename
      • sanitise

        public static String sanitise​(String filename,
                                      String replacement,
                                      FileTools.Compatibility comp)
        Sanitises the name of a file (i.e. without any path) by replacing every illegal character with the designated replacement. The compatibility determines the illegal characters, i. e. a file on a web server must have a simpler name than that on a file system. This may even strip start and end characters.
        If the replacement contains illegal characters, these will be replaced with _.
        Parameters:
        filename - The filename to sanitise. this must not be null.
        replacement - The replacement for illegal characters. If this is null, illegal characters will simply be removed.
        comp - The FileTools.Compatibility of the file name.
        Returns:
        The sanitised filename.
        Throws:
        IllegalArgumentException - If the designated file name becomes empty after replacing (and possibly stripping leading and trailing characters), an IllegalArgumentException will be thrown.
      • getFileName

        public static String getFileName​(String path)
        Gets the file name of the designated path, i. e. removes the trailing path.
        Parameters:
        path - The path of which to get the file name. This may be null.
        Returns:
        The file name of the designated path, null if the path is null.
      • createTempFile

        public static File createTempFile​(File parent,
                                          String child,
                                          boolean directory)
                                   throws IOException
        Creates a new temporary file or directory as child of the designated directory. Created files or directories will be deleted on normal exit of the JVM. If a temporary directory already exists, it will be used but it will not be deleted on exit. An existing file will not be used but an IOException will be thrown.
        Parameters:
        parent - The parent for the directory or file to be created. If this is null, the system temp dir will be used as parent.
        child - The name of the temporary directory or file to be created. This must either be one directory or one file. Do not use several directories or a file and one or more directories. If you need this, call this method for each directory and the file.
        directory - Whether the temporary file system object is a directory (or a file).
        Returns:
        The newly created file or directory.
        Throws:
        IOException - If the temporary
        • directory/file cannot be created,
        • directory already exists but it is not a directory,
        • file already exists,
        an IOException will be thrown.
      • close

        @Deprecated(since="15.0.0",
                    forRemoval=true)
        public static <C extends Closeable> C close​(C closeable)
                                             throws IOException
        Deprecated, for removal: This API element is subject to removal in a future version.
        Use try-with-resources appropriately instead.
        Closes the given Closeable and returns null.
        Type Parameters:
        C -
        Parameters:
        closeable - the Closeable to be closed
        Returns:
        null
        Throws:
        IOException - if Closeable.close() throws an exception
      • toByteArray

        public static byte[] toByteArray​(File file)
                                  throws IOException
        Reads a file into a new byte array. Be careful with large files!
        Parameters:
        file - the file whose content should be loaded into a byte array
        Returns:
        the file's content in a byte array
        Throws:
        IOException - if an I/O error occurs or the file was not found
      • pathPropertyToURLs

        public static URL[] pathPropertyToURLs​(List<String> classPaths,
                                               Logger logger)
        Converts the designated classpaths into an array of URLs by using pathPropertyToURL(String, Logger).
        Parameters:
        classPaths - The classpaths to add as URLs or relative files.
        logger - The logger for log information created by this method.
        Returns:
        All valid URLs contained in the designated class paths or an empty array in case the designated classpaths are null or empty.
        See Also:
        URI.isAbsolute()
      • pathPropertyToURL

        public static URL pathPropertyToURL​(String classPath,
                                            Logger logger)
        Converts the designated classpath into an URL. An illegal URL is interpreted as local file. From this the canonical name is converted to a URL. If this also fails, the corresponding part of the classpath will be ignored.

        For instance, [/C:/Program%20Files/Java/jre1.5.0_07/lib/, /var/lib/security/local_policy.jar, http://aristaflow.de/adept2.jar] is converted to

        • file://localhost/C:/Program%20Files/Java/jre1.5.0_07/lib/
        • file://localhost/var/lib/security/local_policy.jar
        • http://aristaflow.de/adept2.jar
        Parameters:
        classPath - The classpath to as URL or relative files.
        logger - The logger for log information created by this method.
        Returns:
        A valid URL contained in the designated class path null in case the designated classpath is null or cannot be transformed to an URL.
        See Also:
        URI.isAbsolute()
      • getDir

        public static File getDir​(String path,
                                  boolean create)
        Checks if the designated path directory is a valid directory, it exists or can be created and returns it.
        • check if actually a string is supplied
        • create a File object and check if the file exists (if required)
        • check if it is a directory
        • create the directory if appropriate
        Parameters:
        path - The directory to check.
        create - Whether to create the directory if it does not exist.
        Returns:
        The File-instance representing the designated configuration directory or null in case the directory does not exist, cannot be accessed or cannot be created if appropriate.
      • fileAccessible

        public static void fileAccessible​(File file,
                                          String usedFor)
                                   throws IOException
        Checks whether the designated file can be accessed (written to). If it does not exist, its parent directory is checked for whether the file can be created if required.
        Parameters:
        file - The file to check for whether it can be accessed (written to).
        usedFor - A string providing information for what the file is used for.
        Throws:
        IOException - If the designated file cannot be accessed (written to) or cannot be created, an IOException will be thrown.
      • createFileWithParents

        public static void createFileWithParents​(Path path)
                                          throws IOException
        Creates the designated file including all parent directories.
        Parameters:
        path - The file which to create.
        Throws:
        IOException - If there are problems creating the file or its parent directories, an IOException will be thrown.
      • deleteTree

        public static boolean deleteTree​(Path tree,
                                         boolean includeRoot)
                                  throws IOException
        Deletes the designated file path recursively, that is, if it is a directory, its complete contents will be deleted. If an exception occurs, deletion will continue and the exception will be thrown at the end.
        NOTE: It will not be checked, whether the designated file path exists, therefore using Files.exists(Path, java.nio.file.LinkOption...) prior to this method is recommended.
        Parameters:
        tree - The tree which to delete recursively.
        includeRoot - Whether to also delete the designated tree root.
        Returns:
        Whether recursive deletion has been completely successful.
        Throws:
        IOException - If a problems occurs when deleting the designated tree, an IOException will be thrown.
      • getSimpleFileName

        public static String getSimpleFileName​(URL url)
        Gets the (simple) file name the designated URL refers to. This is the part after the last /. If the URL refers to a directory, this will be an empty string if the URL ends with / if not, it will be the name of the directory.
        Parameters:
        url - The URL from which to get the file name.
        Returns:
        The file (or directory) name of the designated URL, which is the part after the last /. null if there is no / (should not occur).
      • urlAccessible

        public static boolean urlAccessible​(URL url,
                                            Logger logger,
                                            boolean write)
        Checks (more or less reliable) whether the designated URL (directory) exists and can be accessed (for reading and/or writing).
        Parameters:
        url - The URL to check.
        logger - The logger for logging messages related to the accessibility of the designated URL. If this is null, no messages will be logged.
        write - Whether the designated URL should also be accessible for writing.
        Returns:
        Whether the designated URL can be accessed.
      • getAllEntriesForClassPath

        public static URL[] getAllEntriesForClassPath​(Path path,
                                                      Logger logger)
        Gets all entries making up a classpath (JAR-files and directories) below the designated tree.
        Parameters:
        path - The tree of which to determine all entries making up a classpath.
        logger - The logger where problems with iterating the tree be logged.
        Returns:
        The classpath with the designated path and all files and directories below it.
      • addAllEntriesForClassPath

        public static List<String> addAllEntriesForClassPath​(Path path,
                                                             List<String> classPath,
                                                             Logger logger)
        Adds all entries making up a classpath (JAR-files and directories) below the designated tree. The designated path will not be part of the classpath.
        Parameters:
        path - The tree of which to determine all entries making up a classpath. This path will not be part of the classpath.
        classPath - The classpath where to add new classpath entries.
        logger - The logger where problems with iterating the tree be logged.
        Returns:
        The classpaths where new entries have been added (the very same as the parameter classPath).
      • findFileAtDefaultLocation

        public static String findFileAtDefaultLocation​(String[] relativePaths,
                                                       String[] absolutePaths)
        Tries to find one of the given relative or absolute paths and returns the first match. Relative paths are relative to the parent of the current working directory and are searched first.
        Parameters:
        relativePaths - Paths to search for, relative to the parent directory of the current working directory.
        absolutePaths - Absolute paths to search for.
        Returns:
        An absolute paths to the first match
      • copy

        public static void copy​(Path src,
                                FilenameFilter filter,
                                Path dest,
                                CopyOption... options)
                         throws IOException
        Copies the designated source path to the designated destination path. If a file name filter is specified the complete directory tree will be copied but only files accepted by the filter. The target may only be a file in case the source is a file too. If source is a directory it will be copied recursively to the target directory.
        Use StandardCopyOptions for replacing files in the destination and/or copying file attributes (e. g. timestamps).
        Parameters:
        src - The source file or directory which to copy, must not be null.
        filter - The filter a file from the source directory needs to match to be copied to the target directory.
        dest - The destination file or directory to which to copy, must not be null.
        options - The copy options like replacing files in the destination or copying file attributes.
        Throws:
        IOException - If there are problems transferring a file, an IOException will be thrown.
      • unzip

        public static void unzip​(File zipFile,
                                 File targetDir)
                          throws IOException
        Unzips the designated zip file to the designated target folder.
        Parameters:
        zipFile - The zip file which to unzip.
        targetDir - The target folder to which to extract the content of the designated zip file.
        Throws:
        IOException - If there are problems reading from the zip file or writing to the target directory or the designated file is a directory or the target directory is a file, an IOException will be thrown.
      • getUniqueFileName

        public static String getUniqueFileName​(String fileName,
                                               Collection<String> allNames)
        Gets the designated file name as unique name with respect to the designated name collection. Uniqueness is established by appending "-1" (or another number) between the file name and the file extension, e. g. fileName-1.txt. Understandably, the number is being incremented by one until the file name is unique.
        Parameters:
        fileName - The file name which should be unique.
        allNames - The file names already known. If this is null, the file name will be returned unchanged.
        Returns:
        The designated file name adapted so that it is unique with respect to the designated name collection.