Class FilenameHelper


  • @Immutable
    public final class FilenameHelper
    extends Object
    All kind of file name handling stuff. This class gives you platform independent file name handling.
    Author:
    Philip Helger
    • Field Detail

      • EXTENSION_SEPARATOR

        public static final char EXTENSION_SEPARATOR
        The file extension separation character.
        See Also:
        Constant Field Values
      • ILLEGAL_FILENAME_CHAR_REPLACEMENT

        public static final char ILLEGAL_FILENAME_CHAR_REPLACEMENT
        The replacement character used for illegal file name characters.
        See Also:
        Constant Field Values
      • UNIX_SEPARATOR

        public static final char UNIX_SEPARATOR
        The Unix path separator character.
        See Also:
        Constant Field Values
      • UNIX_SEPARATOR_STR

        public static final String UNIX_SEPARATOR_STR
        The Unix path separator string.
      • WINDOWS_SEPARATOR

        public static final char WINDOWS_SEPARATOR
        The Windows separator character.
        See Also:
        Constant Field Values
      • WINDOWS_SEPARATOR_STR

        public static final String WINDOWS_SEPARATOR_STR
        The Windows separator string.
      • UNIX_UNC_PREFIX

        public static final String UNIX_UNC_PREFIX
        The prefix to identify UNC paths on Unix based systems
        See Also:
        Constant Field Values
      • WINDOWS_UNC_PREFIX

        public static final String WINDOWS_UNC_PREFIX
        The prefix to identify UNC paths on Windows based systems
        See Also:
        Constant Field Values
      • WINDOWS_UNC_PREFIX_LOCAL1

        public static final String WINDOWS_UNC_PREFIX_LOCAL1
        The prefix to identify local UNC paths on Windows based systems.
        Those no longer work in files in certain Java versions. See https://bugs.openjdk.org/browse/JDK-8285445
        See Also:
        Constant Field Values
      • WINDOWS_UNC_PREFIX_LOCAL2

        public static final String WINDOWS_UNC_PREFIX_LOCAL2
        The prefix to identify local UNC paths on Windows based systems
        Those no longer work in files in certain Java versions. See https://bugs.openjdk.org/browse/JDK-8285445
        See Also:
        Constant Field Values
      • HIDDEN_FILE_PREFIX

        public static final char HIDDEN_FILE_PREFIX
        The prefix used for Unix hidden files
        See Also:
        Constant Field Values
    • Method Detail

      • getIndexOfExtension

        public static int getIndexOfExtension​(@Nullable
                                              String sFilename)
        Returns the index of the last extension separator character, which is a dot.

        This method also checks that there is no directory separator after the last dot. To do this it uses getIndexOfLastSeparator(String) which will handle a file in either Unix or Windows format.

        The output will be the same irrespective of the machine that the code is running on.

        Parameters:
        sFilename - The filename to find the last path separator in. May be null.
        Returns:
        the index of the last separator character, or CGlobal.ILLEGAL_UINT if there is no such character or the input parameter is null.
        See Also:
        getIndexOfLastSeparator(String)
      • getWithoutExtension

        @Nullable
        public static String getWithoutExtension​(@Nullable
                                                 File aFile)
        Get the name of the passed file without the extension. If the file name contains a leading absolute path, the path is returned as well.
        Parameters:
        aFile - The file to extract the extension from. May be null.
        Returns:
        An empty string if no extension was found, the extension without the leading dot otherwise. If the input file is null the return value is null.
        See Also:
        getWithoutExtension(String)
      • getWithoutExtension

        @Nullable
        public static String getWithoutExtension​(@Nullable
                                                 String sFilename)
        Get the passed filename without the extension. If the file name contains a leading absolute path, the path is returned as well.
        Parameters:
        sFilename - The filename to extract the extension from. May be null or empty.
        Returns:
        An empty string if no extension was found, the extension without the leading dot otherwise. If the input string is null the return value is null.
        See Also:
        getIndexOfExtension(String)
      • getExtension

        @Nonnull
        public static String getExtension​(@Nullable
                                          File aFile)
        Get the extension of the passed file.
        Parameters:
        aFile - The file to extract the extension from. May be null.
        Returns:
        An empty string if no extension was found, the extension without the leading dot otherwise. Never null.
        See Also:
        getExtension(String)
      • getExtension

        @Nonnull
        public static String getExtension​(@Nullable
                                          String sFilename)
        Get the extension of the passed filename.
        Parameters:
        sFilename - The filename to extract the extension from. May be null or empty.
        Returns:
        An empty string if no extension was found, the extension without the leading dot otherwise. Never null.
        See Also:
        getIndexOfExtension(String)
      • hasExtension

        public static boolean hasExtension​(@Nullable
                                           File aFile,
                                           @Nonnull
                                           String... aExtensions)
        Check if the passed file has one of the passed extensions. The comparison is done case insensitive even on Unix machines.
        Parameters:
        aFile - The file to check the extension from. May be null or empty.
        aExtensions - An array of extensions (without the leading dot) which are matched case insensitive. May not be null.
        Returns:
        true if the file has one of the passed extensions, else false.
        See Also:
        getExtension(File)
      • hasExtension

        public static boolean hasExtension​(@Nullable
                                           String sFilename,
                                           @Nonnull
                                           String... aExtensions)
        Check if the passed filename has one of the passed extensions. The comparison is done case insensitive even on Unix machines.
        Parameters:
        sFilename - The filename to check the extension from. May be null or empty.
        aExtensions - An array of extensions (without the leading dot) which are matched case insensitive. May not be null.
        Returns:
        true if the filename has one of the passed extensions, else false.
        See Also:
        getExtension(String)
      • getIndexOfLastSeparator

        public static int getIndexOfLastSeparator​(@Nullable
                                                  String sFilename)
        Returns the index of the last directory separator character. This method will handle a file in either Unix or Windows format. The position of the last forward or backslash is returned. The output will be the same irrespective of the machine that the code is running on.
        Parameters:
        sFilename - The filename to find the last path separator in, null returns CGlobal.ILLEGAL_UINT.
        Returns:
        The index of the last separator character, or CGlobal.ILLEGAL_UINT if there is no such character
      • getWithoutPath

        @Nullable
        public static String getWithoutPath​(@Nullable
                                            File aFile)
        Get the name of the passed file without any eventually leading path. Note: if the passed file is a directory, the name of the directory is returned.
        Parameters:
        aFile - The file. May be null.
        Returns:
        The name only or null if the passed parameter is null.
      • getWithoutPath

        @Nullable
        public static String getWithoutPath​(@Nullable
                                            String sAbsoluteFilename)
        Get the name of the passed file without any eventually leading path.
        Parameters:
        sAbsoluteFilename - The fully qualified file name. May be null.
        Returns:
        The name only or null if the passed parameter is null.
        See Also:
        getIndexOfLastSeparator(String)
      • getPath

        @Nullable
        public static String getPath​(@Nullable
                                     String sAbsoluteFilename)
        Get the path of the passed file name without any eventually contained filename.
        Parameters:
        sAbsoluteFilename - The fully qualified file name. May be null.
        Returns:
        The path only including the last trailing path separator character. Returns null if the passed parameter is null.
        See Also:
        getIndexOfLastSeparator(String)
      • getBaseName

        @Nullable
        public static String getBaseName​(@Nullable
                                         File aFile)
        Get the passed filename without path and without extension.
        Example: /dir1/dir2/file.txt becomes file
        Parameters:
        aFile - The file to get the base name from. May be null.
        Returns:
        The base name of the passed parameter. May be null if the parameter was null.
        See Also:
        getWithoutExtension(String)
      • getBaseName

        @Nullable
        public static String getBaseName​(@Nullable
                                         String sAbsoluteFilename)
        Get the passed filename without path and without extension.
        Example: /dir1/dir2/file.txt becomes file
        Parameters:
        sAbsoluteFilename - The filename to get the base name from. May be null.
        Returns:
        The base name of the passed parameter. May be null if the parameter was null.
        See Also:
        getWithoutPath(String), getWithoutExtension(String)
      • getPathUsingUnixSeparator

        @Nullable
        public static String getPathUsingUnixSeparator​(@Nullable
                                                       File aFile)
        Ensure that the path (not the absolute path!) of the passed file is using the Unix style separator "/" instead of the Operating System dependent one.
        Parameters:
        aFile - The file to use. May be null
        Returns:
        null if the passed file is null.
        See Also:
        getPathUsingUnixSeparator(String)
      • getPathUsingUnixSeparator

        @Nullable
        public static String getPathUsingUnixSeparator​(@Nullable
                                                       String sAbsoluteFilename)
        Ensure that the passed path is using the Unix style separator "/" instead of the Operating System dependent one.
        Parameters:
        sAbsoluteFilename - The file name to use. May be null
        Returns:
        null if the passed path is null.
        See Also:
        getPathUsingUnixSeparator(File)
      • getPathUsingWindowsSeparator

        @Nullable
        public static String getPathUsingWindowsSeparator​(@Nullable
                                                          File aFile)
        Ensure that the path (not the absolute path!) of the passed file is using the Windows style separator "\" instead of the Operating System dependent one.
        Parameters:
        aFile - The file to use. May be null
        Returns:
        null if the passed file is null.
        See Also:
        getPathUsingWindowsSeparator(String)
      • getPathUsingWindowsSeparator

        @Nullable
        public static String getPathUsingWindowsSeparator​(@Nullable
                                                          String sAbsoluteFilename)
        Ensure that the passed path is using the Windows style separator "\" instead of the Operating System dependent one.
        Parameters:
        sAbsoluteFilename - The file name to use. May be null
        Returns:
        null if the passed path is null.
        See Also:
        getPathUsingWindowsSeparator(File)
      • isEqualIgnoreFileSeparator

        public static boolean isEqualIgnoreFileSeparator​(@Nullable
                                                         String sAbsoluteFilename1,
                                                         @Nullable
                                                         String sAbsoluteFilename2)
        Check whether the two passed file names are equal, independent of the used separators (/ or \).
        Parameters:
        sAbsoluteFilename1 - First file name. May be null.
        sAbsoluteFilename2 - Second file name. May be null.
        Returns:
        true if they are equal, false otherwise.
        See Also:
        getPathUsingUnixSeparator(String)
      • getSecureFilename

        @Nullable
        public static String getSecureFilename​(@Nullable
                                               String sFilename)
        Avoid 0 byte attack. E.g. file name "test.java.txt" is internally represented as "test.java" but ends with ".txt".
        Note: the passed file name is NOT decoded (e.g. %20 stays %20 and will not be converted to a space).
        Parameters:
        sFilename - The file name to check. May be null.
        Returns:
        null if the input string is null or everything up to the 0-byte.
      • isValidFilename

        public static boolean isValidFilename​(@Nullable
                                              String sFilename)
        Check if the passed file name is valid. It checks for illegal prefixes that affects compatibility to Windows, illegal characters within a filename and forbidden suffixes. This method fits only for filenames on one level. If you want to check a full path, use isValidFilenameWithPaths(String).
        Parameters:
        sFilename - The filename to check. May be null.
        Returns:
        false if the passed filename is null or empty or invalid. true if the filename is not empty and valid.
        See Also:
        containsPathSeparatorChar(String)
      • isValidFilenameWithPaths

        public static boolean isValidFilenameWithPaths​(@Nullable
                                                       String sFilename)
        Check if the passed filename path is valid. In contrast to isValidFilename(String) this method can also handle filenames including paths.
        Parameters:
        sFilename - The filename to be checked for validity.
        Returns:
        true if all path elements of the filename are valid, false if at least one element is invalid
        See Also:
        isValidFilename(String)
      • getAsSecureValidFilename

        @Nullable
        @Nonempty
        public static String getAsSecureValidFilename​(@Nullable
                                                      String sFilename)
        Convert the passed filename into a valid filename by performing the following actions:
        1. Remove everything after a potential \0 character
        2. Remove all characters that are invalid at the end of a file name
        3. Replace all characters that are invalid inside a filename with a underscore
        4. If the filename is invalid on Windows platforms it is prefixed with an underscore.
        Note: this method does not handle Windows full path like "c:\autoexec.bat"
        Parameters:
        sFilename - The filename to be made value. May be null.
        Returns:
        null if the input filename was null or if it consisted only of characters invalid for a filename; the potentially modified filename otherwise but never an empy string.
        See Also:
        getSecureFilename(String)
      • isSecureFilenameCharacter

        public static boolean isSecureFilenameCharacter​(char c)
        Check if the passed character is secure to be used in filenames. Therefore it must be ≥ 0x20 and < 0x80.
        Parameters:
        c - The character to check
        Returns:
        true if it is valid, false if not
      • getAsSecureValidASCIIFilename

        @Nullable
        @Nonempty
        public static String getAsSecureValidASCIIFilename​(@Nullable
                                                           String sFilename)
        Replace all non-ASCII characters from the filename (e.g. German Umlauts) with underscores. Before replacing non-ASCII characters the filename is made valid using getAsSecureValidFilename(String).
        Parameters:
        sFilename - Input file name. May not be null.
        Returns:
        null if the input filename was null. The file name containing only ASCII characters. The returned value is never an empty String.
        See Also:
        getAsSecureValidASCIIFilename(String, char)
      • isPathSeparatorChar

        public static boolean isPathSeparatorChar​(char c)
        Check if the passed character is a path separation character. This method handles both Windows- and Unix-style path separation characters.
        Parameters:
        c - The character to check.
        Returns:
        true if the character is a path separation character, false otherwise.
      • startsWithPathSeparatorChar

        public static boolean startsWithPathSeparatorChar​(@Nullable
                                                          CharSequence s)
        Check if the passed character sequence starts with a path separation character.
        Parameters:
        s - The character sequence to check. May be null or empty.
        Returns:
        true if the character sequences starts with a Windows- or Unix-style path character.
        See Also:
        isPathSeparatorChar(char)
      • endsWithPathSeparatorChar

        public static boolean endsWithPathSeparatorChar​(@Nullable
                                                        CharSequence s)
        Check if the passed character sequence ends with a path separation character.
        Parameters:
        s - The character sequence to check. May be null or empty.
        Returns:
        true if the character sequences ends with a Windows- or Unix-style path character.
        See Also:
        isPathSeparatorChar(char)
      • containsPathSeparatorChar

        public static boolean containsPathSeparatorChar​(@Nullable
                                                        String s)
        Check if the passed String contains at least one path separator char (either Windows or Unix style).
        Parameters:
        s - The string to check. May be null.
        Returns:
        true if the passed string is not null and contains at least one separator.
      • isSystemInternalDirectory

        public static boolean isSystemInternalDirectory​(@Nullable
                                                        File aFile)
        Check if the passed file is a system directory. A system directory is either "." or "..".
        Parameters:
        aFile - The file to be checked. May be null.
        Returns:
        true if the passed file name (not the path) matches any of the special directory names, false of the passed file is null or does not denote a special directory.
        See Also:
        isSystemInternalDirectory(CharSequence)
      • isSystemInternalDirectory

        public static boolean isSystemInternalDirectory​(@Nullable
                                                        Path aFile)
        Check if the passed file is a system directory. A system directory is either "." or "..".
        Parameters:
        aFile - The file to be checked. May be null.
        Returns:
        true if the passed file name (not the path) matches any of the special directory names, false of the passed file is null or does not denote a special directory.
        See Also:
        isSystemInternalDirectory(CharSequence)
      • isSystemInternalDirectory

        public static boolean isSystemInternalDirectory​(@Nullable
                                                        CharSequence s)
        Check if the passed string is a system directory. A system directory is either "." or "..".
        Parameters:
        s - The value to be checked. May be null.
        Returns:
        true if the passed string matches any of the special directory names, false of the passed string is null or does not denote a special directory.
        See Also:
        isSystemInternalDirectory(File)
      • isUNCPath

        public static boolean isUNCPath​(@Nonnull
                                        File aFile)
        Check if the passed file is an UNC path. UNC paths are identified by starting with "//" or "\\".
        Parameters:
        aFile - The file to be checked. May not be null.
        Returns:
        true if the file points to an UNC path, false if not.
        See Also:
        isUNCPath(String)
      • isUNCPath

        public static boolean isUNCPath​(@Nonnull
                                        String sFilename)
        Check if the passed file is an UNC path. UNC paths are identified by starting with "//" or "\\".
        Parameters:
        sFilename - The absolute filename to be checked. May not be null.
        Returns:
        true if the file points to an UNC path, false if not.
        See Also:
        isUNCPath(File)
      • isWindowsLocalUNCPath

        public static boolean isWindowsLocalUNCPath​(@Nonnull
                                                    File aFile)
        Check if the passed file is a Windows local UNC path. This type is identified by starting with "\\?\" or "\\.\".
        Parameters:
        aFile - The file to be checked. May not be null.
        Returns:
        true if the file points to an UNC path, false if not.
        See Also:
        isWindowsLocalUNCPath(String)
      • isWindowsLocalUNCPath

        public static boolean isWindowsLocalUNCPath​(@Nonnull
                                                    String sFilename)
        Check if the passed file is a Windows local UNC path. This type is identified by starting with "\\?\" or "\\.\".
        Parameters:
        sFilename - The absolute filename to be checked. May not be null.
        Returns:
        true if the file points to a Windows local UNC path, false if not.
        See Also:
        isWindowsLocalUNCPath(File)
      • getCleanConcatenatedUrlPath

        @Nonnull
        public static String getCleanConcatenatedUrlPath​(@Nonnull
                                                         String sURL,
                                                         @Nonnull
                                                         String sPath)
        Concatenate a base URL and a sub path incl. the path cleansing. More or less the same as calling getCleanPath (sURL + "/" + sPath)
        Parameters:
        sURL - The base URL. May not be null.
        sPath - The path to append. May not be null.
        Returns:
        The combined, cleaned path.
        See Also:
        getCleanPath(String)
      • ensurePathStartingWithSeparator

        @Nullable
        @CheckReturnValue
        public static String ensurePathStartingWithSeparator​(@Nullable
                                                             String sPath)
        Ensure that the passed path starts with a directory separator character. If the passed path starts with either 92 or 47 no changes are performed.
        Parameters:
        sPath - The path to be checked.
        Returns:
        The path that is ensured to start with the directory separator of the current operating system.
        See Also:
        startsWithPathSeparatorChar(CharSequence)
      • ensurePathEndingWithSeparator

        @Nullable
        @CheckReturnValue
        public static String ensurePathEndingWithSeparator​(@Nullable
                                                           String sPath)
        Ensure that the passed path ends with a directory separator character. If the passed path ends with either 92 or 47 no changes are performed.
        Parameters:
        sPath - The path to be checked.
        Returns:
        The path that is ensured to end with the directory separator of the current operating system.
        See Also:
        endsWithPathSeparatorChar(CharSequence)
      • getRelativeToParentDirectory

        @Nullable
        public static String getRelativeToParentDirectory​(@Nonnull
                                                          File aFile,
                                                          @Nullable
                                                          File aParentDirectory)
        Tries to express the passed file path relative to the passed parent directory. If the parent directory is null or not actually a parent of the passed file, the passed file name will be returned unchanged.
        Parameters:
        aFile - The file which is to be described relatively. May not be null.
        aParentDirectory - The parent directory of the file to which the relative path expression will relate to. May be null.
        Returns:
        The relative path or the unchanged absolute file path using Unix path separators instead of Operating System dependent separator. Or null if the passed file contains a path traversal at the beginning
        See Also:
        getCleanPath(File), startsWithPathSeparatorChar(CharSequence)
      • getAbsoluteWithEnsuredParentDirectory

        @Nullable
        public static String getAbsoluteWithEnsuredParentDirectory​(@Nonnull
                                                                   File aParentDirectory,
                                                                   @Nonnull
                                                                   String sFilePath)
        Get a concatenated absolute path consisting of the parent directory and the file path. It is ensured that the resulting (cleaned) filename is still the same or a child of the passed parent directory. If the file path contains some directory traversal elements (e.g. starting with "..") null is returned.
        Parameters:
        aParentDirectory - The parent directory to be ensured. May not be null.
        sFilePath - The file path to be appended to the passed parent directory. May not be null.
        Returns:
        null if the parent directory would be changed with the passed file path - the concatenated cleaned path otherwise (using Unix separators).
        See Also:
        getRelativeToParentDirectory(File, File), getCleanPath(File)
      • isHiddenFilename

        public static boolean isHiddenFilename​(@Nullable
                                               File aFile)
        Check if the passed filename is a Unix hidden filename.
        Parameters:
        aFile - The file to check. May be null.
        Returns:
        true if the file is not null and the name starts with a dot.
        See Also:
        isHiddenFilename(String)
      • isHiddenFilename

        public static boolean isHiddenFilename​(@Nullable
                                               String sFilename)
        Check if the passed filename is a Unix hidden filename.
        Parameters:
        sFilename - The filename to check. May be null.
        Returns:
        true if the filename is neither null nor empty and starts with a dot.
        See Also:
        isHiddenFilename(File)