Class FilenameUtils

General file name and file path manipulation utilities.

When dealing with file names you can hit problems when moving from a Windows based development machine to a Unix based production machine. This class aims to help avoid those problems.

NOTE: You may be able to avoid using this class entirely simply by using JDK java.io.File File objects and the two argument constructor java.io.File#File(java.io.File, java.lang.String) File(File,String).

Most methods on this class are designed to work the same on both Unix and Windows. Those that don't include 'System', 'Unix' or 'Windows' in their name.

Most methods recognize both separators (forward and back), and both sets of prefixes. See the Javadoc of each method for details.

This class defines six components within a file name (example C:\dev\project\file.txt):

  • the prefix - C:\
  • the path - dev\project\
  • the full path - C:\dev\project\
  • the name - file.txt
  • the base name - file
  • the extension - txt

Note that this class works best if directory file names end with a separator. If you omit the last separator, it is impossible to determine if the file name corresponds to a file or a directory. As a result, we have chosen to say it corresponds to a file.

This class only supports Unix and Windows style names. Prefixes are matched as follows:

Windows:
a\b\c.txt           --> ""          --> relative
\a\b\c.txt          --> "\"         --> current drive absolute
C:a\b\c.txt         --> "C:"        --> drive relative
C:\a\b\c.txt        --> "C:\"       --> absolute
\\server\a\b\c.txt  --> "\\server\" --> UNC

Unix: a/b/c.txt --> "" --> relative /a/b/c.txt --> "/" --> absolute /a/b/c.txt --> "/" --> current user ~ --> "/" --> current user (slash added) ~user/a/b/c.txt --> "user/" --> named user user --> "user/" --> named user (slash added)

Both prefix styles are matched always, irrespective of the machine that you are currently running on.

Origin of code: Excalibur, Alexandria, Tomcat, Commons-Utils.

Since

1.1

Properties

EXTENSION_SEPARATOR: "." = '.'

The extension separator character.

Since

1.4

EXTENSION_SEPARATOR_STR: "." = FilenameUtils.EXTENSION_SEPARATOR

The extension separator String.

Since

1.4

Methods

  • Concatenates a fileName to a base path using normal command line style rules.

    The effect is equivalent to resultant directory after changing directory to the first argument, followed by changing directory to the second argument.

    The first argument is the base path, the second is the path to concatenate. The returned path is always normalized via #normalize(String), thus {@code ..} is handled.

    If {@code pathToAdd} is absolute (has an absolute prefix), then it will be normalized and returned. Otherwise, the paths will be joined, normalized and returned.

    The output will be the same on both Unix and Windows except for the separator character.

    /foo/      + bar        -->  /foo/bar
    /foo       + bar        -->  /foo/bar
    /foo       + /bar       -->  /bar
    /foo       + C:/bar     -->  C:/bar
    /foo       + C:bar      -->  C:bar [1]
    /foo/a/    + ../bar     -->  /foo/bar
    /foo/      + ../../bar  -->  null
    /foo/      + /bar       -->  /bar
    /foo/..    + /bar       -->  /bar
    /foo       + bar/c.txt  -->  /foo/bar/c.txt
    /foo/c.txt + bar        -->  /foo/c.txt/bar [2]
    

    [1] Note that the Windows relative drive prefix is unreliable when used with this method.

    [2] Note that the first parameter must be a path. If it ends with a name, then the name will be built into the concatenated path. If this might be a problem, use #getFullPath(String) on the base path argument.

    Parameters

    • basePath: string

      the base path to attach to, always treated as a path

    • fullFileNameToAdd: string

      the fileName (or path) to attach to the base

    Returns string

    the concatenated path, or null if invalid. Null bytes inside string will be removed

  • Determines whether the {@code parent} directory contains the {@code child} element (a file or directory).

    The files names are expected to be normalized.

    Edge cases:

    • A {@code directory} must not be null: if null, throw IllegalArgumentException
    • A directory does not contain itself: return false
    • A null child file is not contained in any parent: return false

    Parameters

    • canonicalParent: string

      the file to consider as the parent.

    • canonicalChild: string

      the file to consider as the child.

    Returns boolean

    true is the candidate leaf is under by the specified composite. False otherwise.

    Since

    2.2

    See

    FileUtils#directoryContains(File, File)

  • Checks whether two fileNames are equal, optionally normalizing and providing control over the case-sensitivity.

    Parameters

    • fileName1: string

      the first fileName to query, may be null

    • fileName2: string

      the second fileName to query, may be null

    • normalized: boolean = false

      whether to normalize the fileNames

    Returns boolean

    true if the fileNames are equal, null equals null

    Since

    1.3

  • Checks whether two fileNames are equal after both have been normalized.

    Both fileNames are first passed to #normalize(String). The check is then performed in a case-sensitive manner.

    Parameters

    • fileName1: string

      the first fileName to query, may be null

    • fileName2: string

      the second fileName to query, may be null

    Returns boolean

    true if the fileNames are equal, null equals null

  • Checks whether two fileNames are equal after both have been normalized and using the case rules of the system.

    Both fileNames are first passed to #normalize(String). The check is then performed case-sensitive on Unix and case-insensitive on Windows.

    Parameters

    • fileName1: string

      the first fileName to query, may be null

    • fileName2: string

      the second fileName to query, may be null

    Returns boolean

    true if the fileNames are equal, null equals null

  • Checks whether two fileNames are equal using the case rules of the system.

    No processing is performed on the fileNames other than comparison. The check is case-sensitive on Unix and case-insensitive on Windows.

    Parameters

    • fileName1: string

      the first fileName to query, may be null

    • fileName2: string

      the second fileName to query, may be null

    Returns boolean

    true if the fileNames are equal, null equals null

  • Flips the Windows name separator to Linux and vice-versa.

    Parameters

    • ch: string

      The Windows or Linux name separator.

    Returns string

    The Windows or Linux name separator.

  • Gets the base name, minus the full path and extension, from a full fileName.

    This method will handle a file in either Unix or Windows format. The text after the last forward or backslash and before the last dot is returned.

    a/b/c.txt --> c
    a.txt     --> a
    a/b/c     --> c
    a/b/c/    --> ""
    

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

    Parameters

    • fileName: string

      the fileName to query, null returns null

    Returns string

    the name of the file without the path, or an empty string if none exists. Null bytes inside string will be removed

  • Gets the extension of a fileName.

    This method returns the textual part of the fileName after the last dot. There must be no directory separator after the dot.

    foo.txt      --> "txt"
    a/b/c.jpg    --> "jpg"
    a/b.txt/c    --> ""
    a/b/c        --> ""
    

    The output will be the same irrespective of the machine that the code is running on, with the exception of a possible IllegalArgumentException on Windows (see below).

    Note: This method used to have a hidden problem for names like "foo.exe:bar.txt". In this case, the name wouldn't be the name of a file, but the identifier of an alternate data stream (bar.txt) on the file foo.exe. The method used to return ".txt" here, which would be misleading. Commons IO 2.7, and later versions, are throwing an IllegalArgumentException for names like this.

    Parameters

    • fileName: string

      the fileName to retrieve the extension of.

    Returns string

    the extension of the file or an empty string if none exists or {@code null} if the fileName is {@code null}.

    Throws

    IllegalArgumentException Windows only: The fileName parameter is, in fact, the identifier of an Alternate Data Stream, for example "foo.exe:bar.txt".

  • Gets the full path from a full fileName, which is the prefix + path.

    This method will handle a file in either Unix or Windows format. The method is entirely text based, and returns the text before and including the last forward or backslash.

    C:\a\b\c.txt --> C:\a\b\
    ~/a/b/c.txt  --> ~/a/b/
    a.txt        --> ""
    a/b/c        --> a/b/
    a/b/c/       --> a/b/c/
    C:           --> C:
    C:\          --> C:\
    ~            --> ~/
    ~/           --> ~/
    ~user        --> ~user/
    ~user/       --> ~user/
    

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

    Parameters

    • fileName: string

      the fileName to query, null returns null

    Returns string

    the path of the file, an empty string if none exists, null if invalid

  • Gets the full path from a full fileName, which is the prefix + path, and also excluding the final directory separator.

    This method will handle a file in either Unix or Windows format. The method is entirely text based, and returns the text before the last forward or backslash.

    C:\a\b\c.txt --> C:\a\b
    ~/a/b/c.txt  --> ~/a/b
    a.txt        --> ""
    a/b/c        --> a/b
    a/b/c/       --> a/b/c
    C:           --> C:
    C:\          --> C:\
    ~            --> ~
    ~/           --> ~
    ~user        --> ~user
    ~user/       --> ~user
    

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

    Parameters

    • fileName: string

      the fileName to query, null returns null

    Returns string

    the path of the file, an empty string if none exists, null if invalid

  • Gets the name minus the path from a full fileName.

    This method will handle a file in either Unix or Windows format. The text after the last forward or backslash is returned.

    a/b/c.txt --> c.txt
    a.txt     --> a.txt
    a/b/c     --> c
    a/b/c/    --> ""
    

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

    Parameters

    • fileName: string

      the fileName to query, null returns null

    Returns string

    the name of the file without the path, or an empty string if none exists. Null bytes inside string will be removed

  • Gets the path from a full fileName, which excludes the prefix.

    This method will handle a file in either Unix or Windows format. The method is entirely text based, and returns the text before and including the last forward or backslash.

    C:\a\b\c.txt --> a\b\
    ~/a/b/c.txt  --> a/b/
    a.txt        --> ""
    a/b/c        --> a/b/
    a/b/c/       --> a/b/c/
    

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

    This method drops the prefix from the result. See #getFullPath(String) for the method that retains the prefix.

    Parameters

    • fileName: string

      the fileName to query, null returns null

    Returns string

    the path of the file, an empty string if none exists, null if invalid. Null bytes inside string will be removed

  • Gets the path from a full fileName, which excludes the prefix, and also excluding the final directory separator.

    This method will handle a file in either Unix or Windows format. The method is entirely text based, and returns the text before the last forward or backslash.

    C:\a\b\c.txt --> a\b
    ~/a/b/c.txt  --> a/b
    a.txt        --> ""
    a/b/c        --> a/b
    a/b/c/       --> a/b/c
    

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

    This method drops the prefix from the result. See #getFullPathNoEndSeparator(String) for the method that retains the prefix.

    Parameters

    • fileName: string

      the fileName to query, null returns null

    Returns string

    the path of the file, an empty string if none exists, null if invalid. Null bytes inside string will be removed

  • Gets the prefix from a full fileName, such as {@code C:/} or {@code ~/}.

    This method will handle a file in either Unix or Windows format. The prefix includes the first slash in the full fileName where applicable.

    Windows:
    a\b\c.txt           --> ""          --> relative
    \a\b\c.txt          --> "\"         --> current drive absolute
    C:a\b\c.txt         --> "C:"        --> drive relative
    C:\a\b\c.txt        --> "C:\"       --> absolute
    \\server\a\b\c.txt  --> "\\server\" --> UNC
    
    

    Unix: a/b/c.txt --> "" --> relative /a/b/c.txt --> "/" --> absolute /a/b/c.txt --> "/" --> current user ~ --> "/" --> current user (slash added) ~user/a/b/c.txt --> "user/" --> named user user --> "user/" --> named user (slash added)

    The output will be the same irrespective of the machine that the code is running on. ie. both Unix and Windows prefixes are matched regardless.

    Parameters

    • fileName: string

      the fileName to query, null returns null

    Returns string

    the prefix of the file, null if invalid. Null bytes inside string will be removed

  • Returns the length of the fileName prefix, such as {@code C:/} or {@code ~/}.

    This method will handle a file in either Unix or Windows format.

    The prefix length includes the first slash in the full fileName if applicable. Thus, it is possible that the length returned is greater than the length of the input string.

    Windows:
    a\b\c.txt           --> 0           --> relative
    \a\b\c.txt          --> 1           --> current drive absolute
    C:a\b\c.txt         --> 2           --> drive relative
    C:\a\b\c.txt        --> 3           --> absolute
    \\server\a\b\c.txt  --> 9           --> UNC
    \\\a\b\c.txt        --> -1          --> error
    
    

    Unix: a/b/c.txt --> 0 --> relative /a/b/c.txt --> 1 --> absolute ~/a/b/c.txt --> 2 --> current user ~ --> 2 --> current user (slash added) ~user/a/b/c.txt --> 6 --> named user ~user --> 6 --> named user (slash added) //server/a/b/c.txt --> 9 ///a/b/c.txt --> -1 --> error C: --> 0 --> valid filename as only null byte and / are reserved characters

    The output will be the same irrespective of the machine that the code is running on. ie. both Unix and Windows prefixes are matched regardless.

    Note that a leading // (or \\) is used to indicate a UNC name on Windows. These must be followed by a server name, so double-slashes are not collapsed to a single slash at the start of the fileName.

    Parameters

    • fileName: string

      the fileName to find the prefix in, null returns -1

    Returns number

    the length of the prefix, -1 if invalid or null

  • 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 #indexOfLastSeparator(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, with the exception of a possible IllegalArgumentException on Windows (see below).

    Note: This method used to have a hidden problem for names like "foo.exe:bar.txt". In this case, the name wouldn't be the name of a file, but the identifier of an alternate data stream (bar.txt) on the file foo.exe. The method used to return ".txt" here, which would be misleading. Commons IO 2.7, and later versions, are throwing an IllegalArgumentException for names like this.

    Parameters

    • fileName: string

      the fileName to find the last extension separator in, null returns -1

    Returns number

    the index of the last extension separator character, or -1 if there is no such character

    Throws

    IllegalArgumentException Windows only: The fileName parameter is, in fact, the identifier of an Alternate Data Stream, for example "foo.exe:bar.txt".

  • 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

    • fileName: string

      the fileName to find the last path separator in, null returns -1

    Returns number

    the index of the last separator character, or -1 if there is no such character

  • Checks whether the extension of the fileName is one of those specified.

    This method obtains the extension as the textual part of the fileName after the last dot. There must be no directory separator after the dot. The extension check is case-sensitive on all platforms.

    Parameters

    • fileName: string

      the fileName to query, null returns false

    • extensions: string[]

      the extensions to check for, null checks for no extension

    Returns boolean

    true if the fileName is one of the extensions

    Throws

    java.lang.IllegalArgumentException if the supplied fileName contains null bytes

  • Checks whether the extension of the fileName is that specified.

    This method obtains the extension as the textual part of the fileName after the last dot. There must be no directory separator after the dot. The extension check is case-sensitive on all platforms.

    Parameters

    • fileName: string

      the fileName to query, null returns false

    • extension: string

      the extension to check for, null or empty checks for no extension

    Returns boolean

    true if the fileName has the specified extension

    Throws

    java.lang.IllegalArgumentException if the supplied fileName contains null bytes

  • Checks whether the extension of the fileName is one of those specified.

    This method obtains the extension as the textual part of the fileName after the last dot. There must be no directory separator after the dot. The extension check is case-sensitive on all platforms.

    Parameters

    • fileName: string

      the fileName to query, null returns false

    • Rest ...extensions: string[]

      the extensions to check for, null checks for no extension

    Returns boolean

    true if the fileName is one of the extensions

    Throws

    java.lang.IllegalArgumentException if the supplied fileName contains null bytes

  • Normalizes a path, removing double and single dot path steps.

    This method normalizes a path to a standard format. The input may contain separators in either Unix or Windows format. The output will contain separators in the format specified.

    A trailing slash will be retained. A double slash will be merged to a single slash (but UNC names are handled). A single dot path segment will be removed. A double dot will cause that path segment and the one before to be removed. If the double dot has no parent path segment to work with, {@code null} is returned.

    The output will be the same on both Unix and Windows except for the separator character.

    /foo//               -->   /foo/
    /foo/./              -->   /foo/
    /foo/../bar          -->   /bar
    /foo/../bar/         -->   /bar/
    /foo/../bar/../baz   -->   /baz
    //foo//./bar         -->   /foo/bar
    /../                 -->   null
    ../foo               -->   null
    foo/bar/..           -->   foo/
    foo/../../bar        -->   null
    foo/../bar           -->   bar
    //server/foo/../bar  -->   //server/bar
    //server/../bar      -->   null
    C:\foo\..\bar        -->   C:\bar
    C:\..\bar            -->   null
    ~/foo/../bar/        -->   ~/bar/
    ~/../bar             -->   null
    
    The output will be the same on both Unix and Windows including the separator character.

    Parameters

    • fileName: string

      the fileName to normalize, null returns null

    • Optional unixSeparator: boolean

      {@code true} if a unix separator should be used or {@code false} if a windows separator should be used.

    Returns string

    the normalized fileName, or null if invalid. Null bytes inside string will be removed

    Since

    2.0

  • Normalizes a path, removing double and single dot path steps, and removing any final directory separator.

    This method normalizes a path to a standard format. The input may contain separators in either Unix or Windows format. The output will contain separators in the format specified.

    A trailing slash will be removed. A double slash will be merged to a single slash (but UNC names are handled). A single dot path segment will be removed. A double dot will cause that path segment and the one before to be removed. If the double dot has no parent path segment to work with, {@code null} is returned.

    The output will be the same on both Unix and Windows including the separator character.

    /foo//               -->   /foo
    /foo/./              -->   /foo
    /foo/../bar          -->   /bar
    /foo/../bar/         -->   /bar
    /foo/../bar/../baz   -->   /baz
    //foo//./bar         -->   /foo/bar
    /../                 -->   null
    ../foo               -->   null
    foo/bar/..           -->   foo
    foo/../../bar        -->   null
    foo/../bar           -->   bar
    //server/foo/../bar  -->   //server/bar
    //server/../bar      -->   null
    C:\foo\..\bar        -->   C:\bar
    C:\..\bar            -->   null
    ~/foo/../bar/        -->   ~/bar
    ~/../bar             -->   null
    

    Parameters

    • fileName: string

      the fileName to normalize, null returns null

    • Optional unixSeparator: boolean

      {@code true} if a unix separator should be used or {@code false} if a windows separator should be used.

    Returns string

    the normalized fileName, or null if invalid. Null bytes inside string will be removed

    Since

    2.0

  • Removes the extension from a fileName.

    This method returns the textual part of the fileName before the last dot. There must be no directory separator after the dot.

    foo.txt    --> foo
    a\b\c.jpg  --> a\b\c
    a\b\c      --> a\b\c
    a.b\c      --> a.b\c
    

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

    Parameters

    • fileName: string

      the fileName to query, null returns null

    Returns string

    the fileName minus the extension

  • Converts all separators to the system separator.

    Parameters

    • path: string

      the path to be changed, null ignored.

    Returns string

    the updated path.

  • Converts all separators to the Unix separator of forward slash.

    Parameters

    • path: string

      the path to be changed, null ignored.

    Returns string

    the new path.

  • Converts all separators to the Windows separator of backslash.

    Parameters

    • path: string

      the path to be changed, null ignored.

    Returns string

    the updated path.

  • Checks a fileName to see if it matches the specified wildcard matcher, always testing case-sensitive.

    The wildcard matcher uses the characters '?' and '*' to represent a single or multiple (zero or more) wildcard characters. This is the same as often found on DOS/Unix command lines. The check is case-sensitive always.

    wildcardMatch("c.txt", "*.txt")      --> true
    wildcardMatch("c.txt", "*.jpg")      --> false
    wildcardMatch("a/b/c.txt", "a/b/*")  --> true
    wildcardMatch("c.txt", "*.???")      --> true
    wildcardMatch("c.txt", "*.????")     --> false
    
    N.B. the sequence "*?" does not work properly at present in match strings.

    Parameters

    • fileName: string

      the fileName to match on

    • wildcardMatcher: string

      the wildcard string to match against

    Returns boolean

    true if the fileName matches the wildcard string