I need to extract extensions from file names.
I know this can be done for single extensions like .gz
or .tar
by using filePath.lastIndexOf('.')
or using utility methods like FilenameUtils.getExtension(filePath)
from Apache commons-io.
But, what if I have a file with an extension like .tar.gz
? How can I manage files with extensions that contain .
characters?
If you know what extensions are important, you can simply check for them explicitly. You would have a collection of known extensions, like this:
You could get the (first) longest matching extension like this:
So calling
getExtension("file.tar.gz")
would return"tar.gz"
.If you have mixed-case names, perhaps try changing the check to
filename.toLowerCase().endsWith("." + ext)
inside the loop.