Get File Extension for special cases like tar.gz

file, java, utility-method

Solution

If you know what extensions are important, you can simply check for them explicitly. You would have a collection of known extensions, like this:

List<String> EXTS = Arrays.asList("tar.gz", "tgz", "gz", "zip");

You could get the (first) longest matching extension like this:

String getExtension(String fileName) {
  String found = null;
  for (String ext : EXTS) {
    if (fileName.endsWith("." + ext)) {
      if (found == null || found.length() < ext.length()) {
        found = ext;
      }
    }
  }
  return found;
}

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.

Problem

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?

Original source