In this tutorial , we will see how we can get the extension of file in Java. In the next example , we will use lastIndexOf to get the file extension of a file.

 String extension = "";

  int index = fileName.lastIndexOf('.');
  if (index > 0) {
      extension = fileName.substring(index + 1);
  }

The above process, will fail if the directory name or file path includes a dot or double dots AND the file does not have an extension..


  Path: /path/../makefile              -> File Extension: /makefile
  Path: /path/dir.test/makefile        -> File Extension: test/makefile

Example

public class GetFileExtension1 {

    private static final String OUTPUT_FORMAT = "Path: %-30s -> File Extension: %s";

    public static void main(String[] args) {

        String[] files = {
                "/path/foo.txt",
                ".",
                "..",
                "/path/run.exe",
                "/path/makefile",
                "/path/.htaccess",
                "/path/.tar.gz",
                "/path/../makefile",
                "/path/dir.test/makefile"
        };

        for (String file : files) {
            String output = String.format(OUTPUT_FORMAT, file, getFileExtension(file));
            System.out.println(output);
        }

    }

    /**
     * Fail for below cases
     * <p>
     * "/path/../makefile",
     * "/path/dir.test/makefile"
     */
    public static String getFileExtension(String fileName) {
        if (fileName == null) {
            throw new IllegalArgumentException("fileName must not be null!");
        }

        String extension = "";

        int index = fileName.lastIndexOf('.');
        if (index > 0) {
            extension = fileName.substring(index + 1);
        }

        return extension;

    }

}

Output

Path: /path/foo.txt                  -> File Extension: txt
Path: .                              -> File Extension:
Path: ..                             -> File Extension:
Path: /path/run.exe                  -> File Extension: exe
Path: /path/makefile                 -> File Extension:
Path: /path/.htaccess                -> File Extension: htaccess
Path: /path/.tar.gz                  -> File Extension: gz
Path: /path/../makefile              -> File Extension: /makefile
Path: /path/dir.test/makefile        -> File Extension: test/makefile

Now , in the next example we will use the strict version. This example conducts additional checks to ensure that the directory contains a dot and that the file has no extension.

  Path: /path/../makefile              -> File Extension:
  Path: /path/dir.test/makefile        -> File Extension:

The extra checking ensures the last file extension index (position) is always after the last file separator (Windows or Unix).


  if (indexOfLastExtension > indexOflastSeparator) {
      extension = fileName.substring(indexOfLastExtension + 1);
  }

Full example.

import java.util.Map;

public class GetFileExtension2 {

    private static final String OUTPUT_FORMAT = "Path: %-30s -> File Extension: %s";
    private static final String WINDOWS_FILE_SEPARATOR = "\\";
    private static final String UNIX_FILE_SEPARATOR = "/";
    private static final String FILE_EXTENSION = ".";

    public static void main(String[] args) {

        String[] files = {
                "/path/foo.txt",
                ".",
                "..",
                "/path/run.exe",
                "/path/makefile",
                "/path/.htaccess",
                "/path/.tar.gz",
                "/path/../makefile",
                "/path/dir.test/makefile"
        };

        for (String file : files) {
            String output = String.format(OUTPUT_FORMAT, file, getFileExtensionImproved(file));
            System.out.println(output);
        }

    }

    /**
     * Add extra checking for below cases
     * <p>
     * "/path/../makefile",
     * "/path/dir.test/makefile"
     */
    public static String getFileExtensionImproved(String fileName) {

        if (fileName == null) {
            throw new IllegalArgumentException("fileName must not be null!");
        }

        String extension = "";

        int indexOfLastExtension = fileName.lastIndexOf(FILE_EXTENSION);

        // check last file separator, windows and unix
        int lastSeparatorPosWindows = fileName.lastIndexOf(WINDOWS_FILE_SEPARATOR);
        int lastSeparatorPosUnix = fileName.lastIndexOf(UNIX_FILE_SEPARATOR);

        // takes the greater of the two values, which mean last file separator
        int indexOflastSeparator = Math.max(lastSeparatorPosWindows, lastSeparatorPosUnix);

        // make sure the file extension appear after the last file separator
        if (indexOfLastExtension > indexOflastSeparator) {
            extension = fileName.substring(indexOfLastExtension + 1);
        }

        return extension;

    }

}

Output


Path: /path/foo.txt                  -> File Extension: txt
Path: .                              -> File Extension:
Path: ..                             -> File Extension:
Path: /path/run.exe                  -> File Extension: exe
Path: /path/makefile                 -> File Extension:
Path: /path/.htaccess                -> File Extension: htaccess
Path: /path/.tar.gz                  -> File Extension: gz
Path: /path/../makefile              -> File Extension:
Path: /path/dir.test/makefile        -> File Extension:

There is also , different ways to get file extension in Java.. we explained the most useful methods 😉

References

Laisser un commentaire